Note: No global declarations
Call the functions in main through menu
Implement the following :
Circular singlyLinked List with following functions :
1)insert_at_head(node* & head, int val);
2)insert_at_tail(node* & head, int val);
3)display(node* head) ;
4)insert_at_pos(node* & head, int val,int pos);
5)delete_at_head(node* & head);
6)delete_at_tail(node* & head);
7)delete_at_pos(node* & head, int pos)
#include<iostream>
using namespace std;
struct node
{
int item;
struct node *nextNode;
};
struct node *insert(struct node *head, int data)
{
if (head != NULL)
return head;
struct node *tempNode = (struct node*)malloc(sizeof(struct node));
tempNode -> item = data;
head = tempNode;
head -> nextNode = head;
return head;
}
struct node *insert_at_head(struct node *head, int data)
{
if (head == NULL)
return insert(head, data);
struct node *tempNode = (struct node *)malloc(sizeof(struct node));
tempNode -> item = data;
tempNode -> nextNode = head -> nextNode;
head -> nextNode = tempNode;
return head;
}
struct node *insert_at_tail(struct node *head, int data)
{
if (head == NULL)
return insert(head, data);
struct node *tempNode = (struct node *)malloc(sizeof(struct node));
tempNode -> item = data;
tempNode -> nextNode = head -> nextNode;
head -> nextNode = tempNode;
head = tempNode;
return head;
}
struct node *insert_at_pos(struct node *head, int val, int pos)
{
if (head == NULL)
return NULL;
struct node *tempNode, *pNode;
pNode = head -> nextNode;
do
{
if (pNode ->item == val)
{
tempNode = (struct node *)malloc(sizeof(struct node));
tempNode -> item = val;
tempNode -> nextNode = pNode -> nextNode;
pNode -> nextNode = tempNode;
if (pNode == head)
head = tempNode;
return head;
}
pNode = pNode -> nextNode;
} while(pNode != head -> nextNode);
cout <<head-> item << " Not Found." << endl;
return head;
}
void display(node* head) {
while(head !=NULL){
cout<<head->item<<" ";
head = head->nextNode;
}
}
int main()
{
struct Node *head = NULL;
head = insert(head, 6);
head = insert_at_head(head, 4);
head = insert_at_head(head, 2);
head = insert_at_tail(head, 8);
head = insert_at_tail(head, 12);
head = insert_at_pos(head, 10, 8);
display(head);
return 0;
}
Comments
Leave a comment