Answer to Question #258974 in C++ for kinza

Question #258974



Create a program for circular linked list which perform some functions which are as follows:-


1:- Append Node


2:- Prepend Node


3:- Insert Node After a Specific Position


4:- Delete Node


5:- Update Node


6:- Display




1
Expert's answer
2021-10-30T13:32:42-0400
#include<iostream>
#include<malloc.h>
using namespace std;


struct CircularList
{
	int item;
	struct CircularList *nextNode;
};


struct CircularList *addToEmpty(struct CircularList *lastNode, int data)
{
	
	if (lastNode != NULL)
	return lastNode;


	
	struct CircularList *tempNode =	(struct CircularList*)malloc(sizeof(struct CircularList));


	
	tempNode -> item = data;
	lastNode = tempNode;


	
	lastNode -> nextNode = lastNode;


	return lastNode;
}


struct CircularList *addBegin(struct CircularList *lastNode, int data)
{
	if (lastNode == NULL)
		return addToEmpty(lastNode, data);


	struct CircularList *temp = (struct CircularList *)malloc(sizeof(struct CircularList));


	temp -> item = data;
	temp -> nextNode = lastNode -> nextNode;
	lastNode -> nextNode = temp;


	return lastNode;
}


struct CircularList *addEnd(struct CircularList *lastNode, int data)
{
	if (lastNode == NULL)
		return addToEmpty(lastNode, data);
	
	struct CircularList *temp =		(struct CircularList *)malloc(sizeof(struct CircularList));


	temp -> item = data;
	temp -> nextNode = lastNode -> nextNode;
	lastNode -> nextNode = temp;
	lastNode = temp;


	return lastNode;
}


struct CircularList *addAfter(struct CircularList *lastNode, int data, int item)
{
	if (lastNode == NULL)
		return NULL;


	struct CircularList *temp, *p;
	p = lastNode -> nextNode;
	do
	{
		if (p ->item == item)
		{
			temp = (struct CircularList *)malloc(sizeof(struct CircularList));
			temp -> item = data;
			temp -> nextNode = p -> nextNode;
			p -> nextNode = temp;


			if (p == lastNode)
				lastNode = temp;
			return lastNode;
		}
		p = p -> nextNode;
	} while(p != lastNode -> nextNode);


	cout << item << " not present in the list." << endl;
	return lastNode;


}


void traverse(struct CircularList *last)
{
	struct CircularList *p;
	


	if (last == NULL)
	{
		cout << "UnderFlow" << endl;
		return;
	}


	
	p = last -> nextNode;


	
	do
	{
		cout << p -> item << " ";
		p = p -> nextNode;


	}
	while(p != last->nextNode);


}


// Testing code
int main()
{
	struct CircularList *head = NULL;


	head = addToEmpty(head, 6);
	head = addBegin(head, 4);
	head = addBegin(head, 2);
	head = addEnd(head, 8);
	head = addEnd(head, 12);
	head = addAfter(head, 10, 8);


	traverse(head);


	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS