You are to write three separate programs, one each for stacks, queues, and linke
ID: 3726281 • Letter: Y
Question
You are to write three separate programs, one each for stacks, queues, and linked-lists that support the following operations for each data structure in question. Each of your program should include a class definition for "Node" (or chunk), a class definition for the data structure (stack/queue/LL) as well as a main function that should give a "menu" like interface to call the various functions. This "menu" like interface can be easily acheived with a "while(1)" loop and a "switch" statement nested within it, like we did in the last lecture. You can use the stack code we did in class as a reference to finish the rest Functions required for each data structure: 1. Linked list: insertAtHead(int value) Hint: Similar to Stacks, insert at position 1 insertAtPosition(int position, int value) Hint: This should insert a node with value' at any position in the list as long as that position is valid removeFromPosition(int position) Hint: Similar to insert above, this should remove a node from a list as long as position is valid displayContents0)Explanation / Answer
Solution:
Adding at front:
void insertAtHead(struct Node** head_address, int myData)
{
//allocating the node
struct Node* newNode= (struct Node*) malloc(sizeof(struct Node));
//allocating the data
newNode->data = myData;
//Now the newly added node's next will be head
newNode->next = (*head_address);
//moving the head to new node
(*head_address) = newNode;
}
Adding at positiion:
void insertAtPosition(struct Node* prev_address, int myData)
{
if (prev_address== NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct Node* newNode=(struct Node*) malloc(sizeof(struct Node));
newNode->data = myData;
newNode->next = prev_address->next;
prev_address->next = newNode;
}
Display the contents:
void displayContents()
{
node *t=new node;
t=head;
while(t!=NULL)
{
cout<<t->data<<" "; t=t->next;
}
}
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
void insertAtHead(struct Node** head_address, int myData)
{
//allocating the node
struct Node* newNode= (struct Node*) malloc(sizeof(struct Node));
//allocating the data
newNode->data = myData;
//Now the newly added node's next will be head
newNode->next = (*head_address);
//moving the head to new node
(*head_address) = newNode;
}
Adding at positiion:
void insertAtPosition(struct Node* prev_address, int myData)
{
if (prev_address== NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct Node* newNode=(struct Node*) malloc(sizeof(struct Node));
newNode->data = myData;
newNode->next = prev_address->next;
prev_address->next = newNode;
}
Display the contents:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.