#include <cstdio>
struct Node {
int data = -1;
Node *next = NULL;
};
int size(Node *Head) {
int i = 0;
for (Node *Current = Head; Current != NULL; Current = Current -> next)
i++;
return i;
}
void display(Node *Head) {
if (Head == NULL)
printf("List is Empty\n");
for (Node *Current = Head; Current; Current = Current -> next)
printf("%d ", Current -> data);
printf("\n");
}
Node * insertNode(Node *Head) {
int choice, loc, i;
Node *Current, *Previous;
Node *NewNode = new Node;
printf("Enter data: ");
scanf("%d", &NewNode -> data);
printf("1. Add Node to The Beginning\n");
printf("2. Add Node to The Ending\n");
printf("3. Add Node to a Specific Location\n");
printf("Choice: ");
scanf("%d", &choice);
if (choice == 1) {
NewNode -> next = Head;
Head = NewNode;
}
else if (choice == 2) {
if (Head != NULL) {
for (Current = Head; Current -> next != NULL; Current = Current -> next);
Current -> next = NewNode;
}
else
Head = NewNode;
}
else if (choice == 3) {
printf("Enter the Location to Insert the Node: ");
scanf("%d", &loc);
int s = size(Head);
if (s < loc || loc < 0)
printf("Location Out of Bound\n\n");
else {
if (loc == 0) {
NewNode -> next = Head;
Head = NewNode;
}
else {
for (i = 0, Current = Head; Current -> next != NULL; Current = Current -> next, i++) {
if (i == loc) {
i = -1;
break;
}
else
Previous = Current;
}
if (i == -1) {
Previous -> next = NewNode;
NewNode -> next = Current;
}
else if (s == loc)
Current -> next = NewNode;
}
}
}
return Head;
}
Node * removeNode(Node *Head) {
if (Head == NULL)
printf("List is Empty\nNothing to Remove\n");
else {
int loc, i;
Node *Current, *Previous;
printf("Enter the Location of the Node to Remove: ");
scanf("%d", &loc);
for (i = 0, Current = Head; Current != NULL; Current = Current -> next, i++) {
if (i == loc) {
if (Current == Head)
Head = Head -> next;
else
Previous -> next = Current -> next;
delete Current;
i = -1;
break;
}
else
Previous = Current;
}
if (i != -1)
printf("Location Not Found\n\n");
}
return Head;
}
int main() {
Node *Head = NULL;
int choice;
while (1) {
printf("==============\n");
printf("1. Add\n");
printf("2. Remove\n");
printf("3. Display All\n");
printf("4. Exit\n");
printf("==============\n");
printf("Choice: ");
scanf("%d", &choice);
if (choice == 1)
Head = insertNode(Head);
else if (choice == 2)
Head = removeNode(Head);
else if (choice == 3)
display(Head);
else if (choice == 4)
break;
else
printf("Invalid Input. Try Again\n");
printf("\n\n");
}
return 0;
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.