I tried putting dummy statements to find out the problem. It seems the problem occurs at the end of the merge()
function at
p->next=list2;
but I do not know what the problem is.
#include <iostream>
using namespace std;
int value, count, value2, count2,choice;
struct node
{
int data;
node * next;
};
node *list = nullptr;
node *list2 = nullptr;
node * p;
node * q;
node * r;
void insertFront()
{
cout << "ENTER A VALUE=";
cin >> value;
if (list == nullptr)
{
p = new node();
p->data = value;
p->next = nullptr;
list = p;
}
else
{
p = new node();
p->data = value;
p->next = list;
list = p;
}
}
void insertFront2()
{
cout << "ENTER A VALUE=";
cin >> value;
if (list2 == nullptr)
{
r = new node();
r->data = value;
r->next = nullptr;
list2 = r;
}
else
{
r = new node();
r->data = value;
r->next = list2;
list2 = r;
}
}
void delFront()
{
if (list == nullptr)
{
cout << "LIST IS ALREADY EMPTY";
}
else
{
p = list;
list = p->next;
delete(p);
}
}
void display(int choice)
{
int select=choice;
if (select == 1)
{
p = list;
}
if (select == 2)
{
p = list2;
}
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void mergeLists(node *list,node *list2)
{
if (list==nullptr and list2==nullptr){
cout<<"Both lists are empty";
}
else if(list==nullptr && list2!=nullptr){
display(2);
}
else if(list2==nullptr && list!=nullptr){
display(1);
}
if(list!=nullptr && list2!=nullptr){
p=list;
while(p!=nullptr){
p=p->next;
}
p->next=list2;
display(1);
}
}
int main()
{
int choice;
cout << "1) Insert at front " << endl;
cout << "2) Delete at front" << endl;
cout << "7) Merge two lists" << endl;
cout << "9) Display" << endl << endl;
while (choice != 99)
{
cout << "Your choice:";
cin >> choice;
switch (choice)
{
case 1:
{
int sel;
cout << "Enter the list to which you want to enter:\n 1 or 2\nYour choice:";
cin >> sel;
if (sel == 1)
{
insertFront();
}
else if (sel == 2)
{
insertFront2();
}
break;
}
case 2:
{
delFront();
break;
}
case 7:
{
mergeLists(list,list2);
break;
}
case 9:
{
int sel;
cout<<"Select a list to display: 1/2"<<endl;
cin>>sel;
display(sel);
break;
}
case 99:
{
cout << "PROGRAM TERMINATED :)";
break;
}
}
}
return 0;
}