Well,The function InsertAtTheEnd(); is not working as expected. My logic is sound and implementation also pretty accurate,I know i must've done some silly mistake,Would Appreciate if anyone could help.
#include<iostream>
#include<stdlib.h>
usingnamespace std;
void InsertAtnThPosition();
void InsertAtTheend();
void InsertAtBeginning();
void Delete();
void Print();
void Exit();
struct Node
{
int data;
Node *link;
};
Node *head,*temp2,*temp3,*temp4,*temp5,*temp6;
int main()
{
head = NULL; // List Is Empty
int choice;
char ans = 'y';
{
do
{
cout << "\n1.Insert At Beginning\n2.Insert at nTH Position\n3.Insert At The End Of The List\n4.Delete An Element\n5.Print The Linked List\n6.Exit\n";
cin >> choice;
switch(choice)
{
case 1: InsertAtBeginning();
break;
case 2: InsertAtnThPosition();
break;
case 3: InsertAtTheend();
break;
case 4: Delete();
break;
case 5: Print();
break;
case 6: Exit();
break;
default: cout << "\nWRONG CHOICE ENTER AGAIN or PRESS 5 To Exit";
break;
}
}
while (ans == 'y' || ans == 'Y');
}
return 0;
}
void InsertAtBeginning()
{
int x;
cout << "\nEnter The Data:";
cin >> x;
Node *temp = new Node;
temp -> data = x;
temp -> link = NULL;
if (head == NULL)
{
head = temp;
}
elseif (head!= NULL)
{
temp -> link = head ;
head =temp;
}
}
void InsertAtnThPosition()
{
int num,pos;
Node *ptr = new Node;
cout << "\nEnter The Data:";
cin >> num;
cout <<"\nEnter The Position where the Value is to be inserted:";
cin >> pos;
ptr -> data = num;
ptr -> link = NULL;
if (pos == 1)
{
ptr -> link = head; // Set the link of the new node to the node where head points
head = ptr; // store the address of new node to be inserted at 1th position in the head node
return ;
}
else
temp2 = head;
for (int i = 0 ; i < pos -2 ; ++i)
{
temp2 = temp2 -> link; // temp 2 is already pointing at first node
}
ptr -> link = temp2 ->link; /*sets the link of new node the next node */
temp2 ->link = ptr; /* sets the link previous node to the new node */
return ;
}
void InsertAtTheend()
{
temp5 = head;
int num;
cout << "\nEnter The Data:";
cin >> num;
temp6 = new Node;
temp6->data = num;
temp6->link = NULL;
while(temp5!=NULL)
{
temp5=temp5->link;
}
temp5->link=temp6;
return ;
}
void Delete()
{
int del_pos;
cout << "\nEnter The Position Of the node you want to delete (Knowing The List Index here,starts from 1) :";
cin >> del_pos;
temp3 = head;
for (int x = 0 ; x < del_pos -2 ; ++x)
{
temp3 = temp3 -> link; // Reaches the n-1th node
}
temp4 = temp3 -> link;
temp3 ->link = temp4 -> link;
delete temp4 ;
}
void Print()
{
Node *ptr;
ptr = head;
cout << "\nNow The Linked List Is:\n";
while(ptr!= NULL)
{
cout << endl << ptr -> data;
ptr = ptr -> link;
}
}
void Exit()
{
exit(1);
}
}
Lines 103-107: the while loop doesn't end until temp5 is exactly null, so at line 107 temp5 is definitely null, making the access illegal.
You need to loop until temp5->link is null.
Also, get rid of line 16. Declare the variables locally in the functions that use them and give them more descriptive names.