-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
155 lines (120 loc) · 2.37 KB
/
LinkedList.cpp
File metadata and controls
155 lines (120 loc) · 2.37 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head = NULL;
Node* tail = NULL;
void insert_node( int new_data)
{
Node* new_node = (Node*)(malloc(sizeof(struct Node))); // create a memory for this node.
new_node -> data = new_data; // assign data to node.
new_node -> next = NULL; // make the next poiter NULL
//head = new_node; //
if (head == NULL)
{
head = new_node;
tail = new_node;
}
else
{
tail -> next = new_node;
tail = new_node;
}
}
void delete_at_position(int pos)
{
Node* prev = new Node;
Node* current = new Node;
current = head;
for (int i = 1; i < pos; i++)
{
prev = current;
current = current -> next;
}
prev -> next = prev -> next -> next;
delete current;
}
void insert_start( int new_data)
{
Node* new_node = (Node*)(malloc(sizeof(struct Node))); // create a memory for this node.
new_node -> data = new_data; // assign data to node.
new_node -> next = head; // make the next poiter NULL
head = new_node;
}
void insert_position(int pos, int value)
{
Node* prev = new Node;
Node* current = new Node;
Node* post = new Node;
current = head;
for (int i = 1; i < pos; i++)
{
prev = current;
current = current -> next;
}
prev -> next = post;
post -> data = value;
post -> next = current;
}
void Display()
{
Node* ptr;
ptr = head;
while (ptr != NULL)
{
cout << ptr -> data << endl;
ptr = ptr -> next;
}
}
int main()
{
insert_node(5);
insert_node(6);
insert_node(7);
insert_node(8);
insert_node(9);
insert_node(10);
insert_start( 11);
delete_at_position(5);
insert_position(3, 3);
Display();
return 0;
}
/*
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next; // Pointer to next node in SLL
};
int main()
{
Node* head = NULL;
Node* first = NULL;
Node* second = NULL;
Node* third = NULL;
head = new Node();
first = new Node();
second = new Node();
third = new Node();
head -> data = 1;
head -> next = first;
first -> data = 2;
first -> next = second;
second -> data = 3;
second -> next = third;
third -> data = 4;
third -> next = NULL;
Node* ptr;
ptr = head;
while (ptr != NULL)
{
cout << ptr -> data << " ";
ptr = ptr -> next;
}
return 0;
}
*/