//Insert at nth position linked list C++.
//This program inserts every where except the first location i.e. does not insert at head.
//This program inserts every where except the first location i.e. does not insert at head.
#include <iostream>
using namespace std;
struct node{
int id;
node *next;
};
void print (node *h);
int main(){
node *head = 0, *tail = 0;
while (1){
int n;
cout << "1. New Entry." << endl;
cout << "2. Print all." << endl;
cin >> n;
if ( n == 1){
cout << "After which ID? "; int id; cin >> id;
node *newPtr = new node;
newPtr -> next = NULL;
//Finding the id.
node *p = head;
while (p!=NULL){
if (p->id == id){
break;
}
p = p->next;
}//If id found the p will point to the node after which we are going to insert.
if (p == NULL)//If id not found.
cout << "ID Not in the linked list.";
if (head == NULL){
head = newPtr;
tail = newPtr;
}
else//If id found the p will point to the node after which we insert.
{//Inserting.
newPtr ->next = p->next;
p->next = newPtr;
}
cout << "\nAssign ID: ";
cin >> newPtr->id;
}
else if(n==2){
print(head);
}
else{
cout << "BY"<< endl;
return 0;
}
}
}
void print (node *h){
while (h!=NULL){
cout << "ID: ";
cout << h->id << endl << endl;
h = h->next;
}
}
No comments:
Post a Comment