Insert at head linked list C++
Solution://Insertion 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){
node *newPtr = new node;
newPtr -> next = NULL;
if (head == NULL){
head = newPtr;
tail = newPtr;
}
else{
newPtr->next = head;
head = newPtr;
}
cout << "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