-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked list (create, insert, delete).cpp
96 lines (82 loc) · 1.84 KB
/
linked list (create, insert, delete).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
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int info;
struct node *next;
};
struct node *first, *last;
struct node *p;
//from head
void insertFirst(int infoNew){
struct node *tmp = (struct node*) malloc(sizeof(struct node));
tmp->info = infoNew;
tmp->next = first;
first = tmp;
}
//from end
//slower than insertLast2 function
void insertLast1(int infoNew){
struct node *tmp = (struct node*) malloc(sizeof(struct node));
tmp->info = infoNew;
tmp->next = NULL;
p = first;
while(p->next != NULL)
p = p->next; // next node
p->next = tmp;
}
//from tail
void insertLast2(int infoNew){
struct node *tmp = (struct node*) malloc(sizeof(struct node));
tmp->info = infoNew;
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
void deleteFirst(){
struct node *tmp;
tmp = first;
first = tmp->next; //first = first->next;
free(tmp);
}
void deleteLast(){
struct node *tmp;
tmp = first;
while(tmp->next != last) //before last node
tmp = tmp->next;
last = tmp;
last->next = NULL;
free(tmp->next);
}
int main()
{
int count = 0;
struct node *one = (struct node*) malloc(sizeof(struct node));
struct node *two = (struct node*) malloc(sizeof(struct node));
struct node *three = (struct node*) malloc(sizeof(struct node));
struct node *tmp;
one->info = 1;
two->info = 2;
three->info = 3;
one->next = two;
two->next = three;
three->next = NULL;
first = one;
last = three;
int infoNew;
cin >> infoNew;
insertFirst(infoNew);
insertLast1(infoNew);
insertLast2(infoNew);
deleteFirst();
deleteLast();
tmp = first; //initial node
//output info of linked list from first to last
while(tmp != NULL){
cout << tmp->info << endl;
tmp = tmp->next;
count++;
}
cout << "There " << count << " linkedlist" << endl;
}