Question: Design and Implement a double linked list in C++ with the following operations: a- Create n nodes b- Delete from the end c- Insert at
Design and Implement a double linked list in C++ with the following operations:
a- Create "n" nodes b- Delete from the end c- Insert at the beginnin
I have it almost complete. I just need to fix the function void insertdata(int x) since it does not insert data at the begining of the node as it is suppoused to do. Could somebody fix that function for me? This is the code I have so far:
#include
#include
using namespace std;
//Define node structure
struct node
{
int data;
node *prev;
node *next;
};
node *top = NULL;
//Creates a node
node *getnode()
{
node *newnode;
newnode = (node*)malloc(1000);
cout << " Enter Data: ";
cin >> newnode->data;
newnode->next = NULL;
return newnode;
}
//Insert date at the beginning
void insertdata(int x)
{
node *newnode, *temp, *prev;
int pos, nodectr;
int ctr = 1;
cout << " Enter the data to insert: ";
newnode = getnode();
if (top == NULL)
{
top = new node;
top->data = x;
top->next = NULL;
top->prev = NULL;
}
else
{
node *n = new node;
n->data = x;
n->next = top;
n->prev = NULL;
top->prev = n;
top = n;
}
}
//Display the list
void displayList()
{
cout << "Elements : ";
node *disp = top;
while (disp != NULL)
{
cout << " " << disp->data;
if (disp->next == NULL)
{
break;
}
disp = disp->next;
}
}
//Delete last node
void deleteLast()
{
node *del = top;
node *prev;
while (del->next != NULL)
{
prev = del;
del = del->next;
}
prev->next = NULL;
}
//Creates a list with size N
void creatlist(int n)
{
int i;
node *newnode;
node * temp;
for (i = 0; i < n; i++)
{
newnode = getnode();
if (top == NULL)
{
top = newnode;
}
else
{
temp = top;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
}
}
int main()
{
node n;
char ch;
int no;
do
{
cout << endl << "a - Create \"n\" nodes.";
cout << endl << "b - Delete from the end.";
cout << endl << "c - Insert at the begining.";
cout << endl << "d - Display.";
cout << endl << "q - Quit.";
cout << endl << "Please enter your choice: ";
cin >> ch;
switch (ch)
{
case 'A': case 'a':
cout << " Enter the size of Linked List: ";
cin >> no;
creatlist(no);
break;
case 'B': case 'b':
{
deleteLast();
cout << "Last element was deleted";
}
break;
case 'C': case 'c':
insertdata(no);
break;
case 'D': case 'd':
displayList();
break;
case 'Q': case 'q':
exit(0);
default:
cout << " Invalid choice, try again";
}
} while (1);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
