Created
July 16, 2017 18:47
-
-
Save amulyagaur/a7443423f84cc7970579ae46685bd4a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
#define endl '\n' | |
struct node | |
{ | |
int data; | |
struct node* next; | |
}; | |
node* InsertAtHead(node* head,int x) | |
{ | |
node* temp = new node(); | |
temp->data =x; | |
temp->next=head; | |
head =temp; | |
return head; | |
} | |
void print_list(node* head) | |
{ | |
while(head!=NULL) | |
{ | |
cout<<head->data<<endl; | |
head=head->next; | |
} | |
return; | |
} | |
node* InsertAtEnd(node* head,int x) | |
{ | |
node* temp = new node(); | |
temp->data = x; | |
temp->next=NULL; | |
node* temp1 = head; | |
while(temp1->next!=NULL) | |
temp1 = temp1->next; | |
temp1->next = temp; | |
return head; | |
} | |
node* InsertAtPos(node* head,int x,int n) | |
{ | |
node* temp = new node(); | |
temp->data = x; | |
temp->next=NULL; | |
//if one has to insert at the front | |
if(n==1) | |
{ | |
temp->next = head; | |
head=temp; | |
return head; | |
} | |
//iterate to (n-1)th position | |
node* temp1 = head; | |
for(int i=1;i<(n-1);i++) | |
temp1 = temp1->next; | |
temp->next= temp1->next; | |
temp1->next=temp; | |
return head; | |
} | |
int main() | |
{ | |
node* head = NULL; //head pointer initially set to NULL | |
head = InsertAtHead(head,5); // list now is: 5->NULL | |
head = InsertAtHead(head,18); // list now is: 18->5->NULL | |
head = InsertAtHead(head,50); // list now is: 50->18->5->NULL | |
head = InsertAtHead(head,15); // list now is: 15->50->18->5->NULL | |
print_list(head); | |
cout<<endl; | |
head = InsertAtEnd(head,20); // list now is: 15->50->18->5->20->NULL | |
head = InsertAtEnd(head,11); // list now is: 15->50->18->5->20->11->NULL | |
print_list(head); | |
cout<<endl; | |
head = InsertAtPos(head,12,4); // list now is: 15->50->18->12->5->20->11->NULL | |
print_list(head); | |
cout<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment