-
Notifications
You must be signed in to change notification settings - Fork 2
/
link1.cpp
108 lines (83 loc) · 1.83 KB
/
link1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node* next;
};
void printList(node* n)
{
while (n!=NULL)
{
cout<<n->data<<" ";
n=n->next;
}
}
void insertAtFirst(node** head_ref,int newdata)
{
//1. allocate node
node* newnode =new node();
//2. put in the data
newnode->data=newdata;
//insert as first
//3. make next of new node as head
newnode->next=(*head_ref);
//4. move the head to point to the new node
(*head_ref)=newnode;
}
void insertAfter(node* prev_node,int newdata)
{
if(prev_node==NULL)
{
cout<<"empty";
return;
}
node* newnode=new node();
newnode->data=newdata;
newnode->next=prev_node->next;
prev_node->next=newnode;
}
void insertAtLast(node** head_ref,int newdata)
{
//1. allocate node
node* newnode=new node();
//2.allocate data
newnode->data=newdata;
newnode->next=NULL;
node* last=*head_ref;
while(last!=NULL)
{
last=last->next;
}
last->next=newnode;
return;
}
int main()
{
node* head=NULL;
node* second=NULL;
node* third=NULL;
head=new node();
second=new node();
third=new node();
head->data=1;
head->next=second;
second->data=2;
second->next=third;
third->data=3;
third->next=NULL;
cout<<"\n************************************************"<<endl;
printList(head);
cout<<"\n************************************************"<<endl;
insertAtLast(&head,8);
printList(head);
cout<<"\n************************************************"<<endl;
insertAfter(third->next,9);
printList(head);
cout<<"\n************************************************"<<endl;
insertAtFirst(&head,6);
printList(head);
return 0;
}