Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cstdlib>
- struct Node {
- int data;
- Node *next;
- } *Head;
- int count() {
- int c = 0;
- for (Node *Current = Head; Current != NULL; Current = Current -> next)
- c++;
- return c;
- }
- int display() {
- if (Head == NULL)
- printf("List is Empty");
- for (Node *Current = Head; Current != NULL; Current = Current -> next)
- printf("%d ", Current -> data);
- printf("\n\n");
- }
- void add(int num) {
- Node *NewNode = (Node *) malloc(sizeof(Node));
- NewNode -> data = num;
- NewNode -> next = NULL;
- if (Head != NULL)
- NewNode -> next = Head;
- Head = NewNode;
- }
- void addAfter(int num, int loc) {
- int i;
- Node *left, *right, *NewNode;
- right = Head;
- for (i = 0; i < loc; i++) {
- left = right;
- right = right -> next;
- }
- NewNode = (Node *) malloc(sizeof(Node));
- NewNode -> data = num;
- left -> next = NewNode;
- NewNode -> next = right;
- }
- void append(int num) {
- Node *NewNode = (Node *) malloc(sizeof(Node));
- NewNode -> data = num;
- NewNode -> next = NULL;
- Node *Current = Head;
- while (Current -> next != NULL)
- Current = Current -> next;
- Current -> next = NewNode;
- }
- void insert(int num) {
- int loc;
- int c = count();
- while (1) {
- printf("Enter the Location: ");
- scanf("%d", &loc);
- if (loc > c || loc < 0)
- printf("Invalid Location.\nMaximum Available Location is: %d\n\n", c);
- else
- break;
- }
- if (loc == 0)
- add(num);
- else if (loc < count())
- addAfter(num, loc);
- else
- append(num);
- }
- int Delete(int num) {
- for (Node *Current = Head, *Previous; Current != NULL; Previous = Current, Current = Current -> next) {
- if (Current -> data == num) {
- if (Current == Head)
- Head = Head -> next;
- else
- Previous -> next = Current -> next;
- free(Current);
- return 1;
- }
- }
- return 0;
- }
- int main() {
- int choice, num;
- Head = NULL;
- while (1) {
- printf("List Operations: \n");
- printf("================\n");
- printf("1. Add\n");
- printf("2. Display\n");
- printf("3. Delete\n");
- printf("4. Size\n");
- printf("5. Exit\n");
- printf("Choice: ");
- scanf("%d", &choice);
- switch (choice) {
- case 1: {
- printf("Enter the Number to Add: ");
- scanf("%d", &num);
- insert(num);
- break;
- }
- case 2: {
- display();
- break;
- }
- case 3: {
- if (Head == NULL)
- printf("List is Empty. Nothing to Delete.\n");
- else {
- printf("Enter Number to Delete: ");
- scanf("%d", &num);
- if (Delete(num) == 1)
- printf("Successfully Deleted %d\n", num);
- else
- printf("%d Not Deleted.\nValue Might Not Found\n", num);
- }
- break;
- }
- case 4: {
- printf("Size of The list is %d\n", count());
- break;
- }
- case 5: {
- exit(0);
- }
- default: {
- printf("Invalid Input. Try Again\n");
- }
- }
- printf("\n\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement