0% found this document useful (0 votes)
3 views

Linked List

Uploaded by

sharayud2806
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Linked List

Uploaded by

sharayud2806
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Linked List

• Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
• A node contains two fields i.e. data stored at that particular address and the pointer
which contains the address of the next node in the memory.
• The last node of the list contains pointer to the null.


Uses of Linked List

• The list is not required to be contiguously present in the memory. The node can
reside any where in the memory and linked together to make a list. This achieves
optimized utilization of space.
• list size is limited to the memory size and doesn't need to be declared in advance.
• Empty node can not be present in the linked list.
• We can store values of primitive types or objects in the singly linked list.

Singly linked list or One way chain

Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist
of two parts: data part and link part. Data part of the node stores actual information that is to
be represented by the node while the link part of the node stores the address of its immediate
successor.

One way chain or singly linked list can be traversed only in one direction. In other words, we
can say that each node contains only next pointer, therefore we can not traverse the list in the
reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in a
linked list as shown in the figure.

In the above figure, the arrow represents the links. The data part of every node contains the
marks obtained by the student in the different subject. The last node in the list is identified by
the null pointer which is present in the address part of the last node. We can have as many
elements we require, in the data part of the list.

Operations on Singly Linked List

There are various operations which can be performed on singly linked list. A list of all such
operations is given below.

Node Creation

Linked List in C

1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };
8. struct node *head;
9.
10. void beginsert ();
11. void lastinsert ();
12. void randominsert();
13. void begin_delete();
14. void last_delete();
15. void random_delete();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.D
elete from Beginning\n
27. 5.Delete from last\n6.Delete node after specified location\n7.Search for an element\
n8.Show\n9.Exit\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. beginsert();
34. break;
35. case 2:
36. lastinsert();
37. break;
38. case 3:
39. randominsert();
40. break;
41. case 4:
42. begin_delete();
43. break;
44. case 5:
45. last_delete();
46. break;
47. case 6:
48. random_delete();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void beginsert()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *) malloc(sizeof(struct node *));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter value\n");
76. scanf("%d",&item);
77. ptr->data = item;
78. ptr->next = head;
79. head = ptr;
80. printf("\nNode inserted");
81. }
82.
83. }
84. void lastinsert()
85. {
86. struct node *ptr,*temp;
87. int item;
88. ptr = (struct node*)malloc(sizeof(struct node));
89. if(ptr == NULL)
90. {
91. printf("\nOVERFLOW");
92. }
93. else
94. {
95. printf("\nEnter value?\n");
96. scanf("%d",&item);
97. ptr->data = item;
98. if(head == NULL)
99. {
100. ptr -> next = NULL;
101. head = ptr;
102. printf("\nNode inserted");
103. }
104. else
105. {
106. temp = head;
107. while (temp -> next != NULL)
108. {
109. temp = temp -> next;
110. }
111. temp->next = ptr;
112. ptr->next = NULL;
113. printf("\nNode inserted");
114.
115. }
116. }
117. }
118. void randominsert()
119. {
120. int i,loc,item;
121. struct node *ptr, *temp;
122. ptr = (struct node *) malloc (sizeof(struct node));
123. if(ptr == NULL)
124. {
125. printf("\nOVERFLOW");
126. }
127. else
128. {
129. printf("\nEnter element value");
130. scanf("%d",&item);
131. ptr->data = item;
132. printf("\nEnter the location after which you want to insert ");
133. scanf("\n%d",&loc);
134. temp=head;
135. for(i=0;i<loc;i++)
136. {
137. temp = temp->next;
138. if(temp == NULL)
139. {
140. printf("\ncan't insert\n");
141. return;
142. }
143.
144. }
145. ptr ->next = temp ->next;
146. temp ->next = ptr;
147. printf("\nNode inserted");
148. }
149. }
150. void begin_delete()
151. {
152. struct node *ptr;
153. if(head == NULL)
154. {
155. printf("\nList is empty\n");
156. }
157. else
158. {
159. ptr = head;
160. head = ptr->next;
161. free(ptr);
162. printf("\nNode deleted from the begining ...\n");
163. }
164. }
165. void last_delete()
166. {
167. struct node *ptr,*ptr1;
168. if(head == NULL)
169. {
170. printf("\nlist is empty");
171. }
172. else if(head -> next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nOnly node of the list deleted ...\n");
177. }
178.
179. else
180. {
181. ptr = head;
182. while(ptr->next != NULL)
183. {
184. ptr1 = ptr;
185. ptr = ptr ->next;
186. }
187. ptr1->next = NULL;
188. free(ptr);
189. printf("\nDeleted Node from the last ...\n");
190. }
191. }
192. void random_delete()
193. {
194. struct node *ptr,*ptr1;
195. int loc,i;
196. printf("\n Enter the location of the node after which you want to perform deletion \n
");
197. scanf("%d",&loc);
198. ptr=head;
199. for(i=0;i<loc;i++)
200. {
201. ptr1 = ptr;
202. ptr = ptr->next;
203.
204. if(ptr == NULL)
205. {
206. printf("\nCan't delete");
207. return;
208. }
209. }
210. ptr1 ->next = ptr ->next;
211. free(ptr);
212. printf("\nDeleted node %d ",loc+1);
213. }
214. void search()
215. {
216. struct node *ptr;
217. int item,i=0,flag;
218. ptr = head;
219. if(ptr == NULL)
220. {
221. printf("\nEmpty List\n");
222. }
223. else
224. {
225. printf("\nEnter item which you want to search?\n");
226. scanf("%d",&item);
227. while (ptr!=NULL)
228. {
229. if(ptr->data == item)
230. {
231. printf("item found at location %d ",i+1);
232. flag=0;
233. }
234. else
235. {
236. flag=1;
237. }
238. i++;
239. ptr = ptr -> next;
240. }
241. if(flag==1)
242. {
243. printf("Item not found\n");
244. }
245. }
246.
247. }
248.
249. void display()
250. {
251. struct node *ptr;
252. ptr = head;
253. if(ptr == NULL)
254. {
255. printf("Nothing to print");
256. }
257. else
258. {
259. printf("\nprinting values . . . . .\n");
260. while (ptr!=NULL)
261. {
262. printf("\n%d",ptr->data);
263. ptr = ptr -> next;
264. }
265. }
266. }
What is Linked List?
When we want to work with an unknown number of data values, we use a linked list data
structure to organize that data. The linked list is a linear data structure that contains a
sequence of elements such that each element links to its next element in the sequence. Each
element in a linked list is called "Node"

Why do we need linked lists?

We need linked lists for the various advantages listed below,

• A linked list is a linear data structure that dynamically stores a group of data
segments.
• These data segments are represented by nodes, which are connected by links or
pointers.
• Each node has information stored in a linked list and a reference to the location of its
subsequent node.
• The final node has null in its second field to avoid it will be pointing to no node


• A linked list's size can be increased or decreased as needed.
• It does not take up much memory space.

The question is fairly simple - If we have a linear data structure in arrays, why do we
even need linked lists?

Because, in an array, it’s much more difficult to insert or add an element. Even in a
dynamic array, all the other elements would have to shift in order to make space if we
have to add an element at the start of the index.

Also, there is a possibility that you’d need to allocate more memory space to the array
before inserting an element.

This is where linked lists find their significance-


Representation of linked lists

We can visualize a linked list as a chain of nodes; where every node contains a data field and
a reference link to the next node in the list.

The first node in the sequence is termed as ‘head’. And we can identify the last node as the
one which points to ‘Null’.

Each node consists of -

• A data field
• Reference to the next node
• Structure of a node in C language-
• struct node
• {
• int data;
• struct node *next;
• };
• Let’s make a simple linked list with three items to understand this better.
Following are the various operations to perform the required action on a linked list:

• Traversal - To access each element of the linked list.


• Insertion - To add/insert a new node to the list.
• Deletion - To remove ane existing node from the list.
• Search - To find a node in the list.
• Sort - To sort the nodes.

What is Single Linked List?


Simply a list is a sequence of data, and the linked list is a sequence of data linked with each
other.
The formal definition of a single linked list is as follows...

Single linked list is a sequence of elements in which every element has link to its next
element in the sequence.

In any single linked list, the individual element is called as "Node". Every "Node" contains
two fields, data field, and the next field. The data field is used to store actual value of the
node and next field is used to store the address of next node in the sequence.

The graphical representation of a node in a single linked list is as follow

Importent Points to be Remembered


In a single linked list, the address of the first node is always stored in a reference node
known as "front" (Some times it is also known as "head").
Always next part (reference part) of the last node must be NULL.

Example
Basic Operations in Linked List

The basic operations in the linked lists are insertion, deletion, searching, display, and deleting
an element at a given key. These operations are performed on Singly Linked Lists as given
below

−Linked List - Insertion Operation

Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has
to be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C
(RightNode). Then point B.next to C −

NewNode.next -> RightNode;


It should look like this −

Now, the next node at the left should point to the new node.

LeftNode.next -> NewNode;


This will put the new node in the middle of the two. The new list should look like this –
Insertion in linked list can be done in three different ways. They are explained as follows −

Insertion at Beginning

In this operation, we are adding an element at the beginning of the list.

Algorithm
1. START
2. Create a node to store the data
3. Check if the list is empty
4. If the list is empty, add the data to the node and
assign the head pointer to it.
5. If the list is not empty, add the data to a node and link to the
current head. Assign the head to the newly added node.
6. END

Example: Let's take an example of singly linked list is 20->30->40 and we want to insert 10
at the head, then the linked list becomes 10->20->30->40.
Insertion at Ending

In this operation, we are adding an element at the ending of the list.

Algorithm
1. START
2. Create a new node and assign the data
3. Find the last node
4. Point the last node to new node
5. END

The new node is always added after the last node of the linked list. Let's take an example If
the given linked list is 20->30->40 and we want to insert 50 at the end of the linked list, then
the linked list becomes 20->30->40->50.
Insertion at Ending

In this operation, we are adding an element at the ending of the list.

Algorithm

START
2. Create a new node and assign the data
3. Find the last node
4. Point the last node to new node
5. END
Insertion at a Given Position

In this operation, we are adding an element at any position within the list.

Algorithm
1. START
2. Create a new node and assign data to it
3. Iterate until the node at position is found
4. Point first to new first node
5. END
Linked List - Deletion Operation

Deletion is also a more than one step process. We shall learn with pictorial representation.
First, locate the target node to be removed, by using searching algorithms.
The left (previous) node of the target node now should point to the next node of the target
node –

LeftNode.next -> TargetNode.next;

This will remove the link that was pointing to the target node. Now, using the following code,
we will remove what the target node is pointing at.
TargetNode.next -> NULL;

We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.

Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the
new node will point to NULL.

Deletion in linked lists is also performed in three different ways. They are as follows −

Deletion at Beginning

In this deletion operation of the linked, we are deleting an element from the beginning of the
list. For this, we point the head to the second node.
Algorithm
1. START
2. Assign the head pointer to the next node in the list
3. END

Deletion at Ending

In this deletion operation of the linked, we are deleting an element from the ending of the list.

Algorithm
1. START
2. Iterate until you find the second last element in the list.
3. Assign NULL to the second last element in the list.
4. END

Deletion at a Given Position

In this deletion operation of the linked, we are deleting an element at any position of the list.

Algorithm
1. START
2. Iterate until find the current node at position in the list.
3. Assign the adjacent node of current node in the list
to its previous node.
4. END

Types of linked lists

There are 4 key types of linked lists-

Singly linked list

Till now we have talked about singly linked lists. It is the most commonly used linked list
containing two parts- the data field, and the reference pointer to the next element.

It is the most basic linked list, with each node containing some data and a reference to the
subsequent node of the same data type.
In a singly linked list, only forward traversal is possible; as it has only one
pointer that points to the next node. For the same reason, it is also termed a
‘one-way chain’.

Doubly linked list

A doubly linked list contains two pointers- one pointing forward and the other one pointing
back to the previous node.

A doubly linked list, also known as a two-way linked list, is an advanced version of linked
list that carries a pointer to both the following and earlier nodes in the chain.

A doubly-linked list contains three parts, including, of course, the data part.

three nodes - 1,2, and 3 with addresses A, B, and C respectively. They will be represented in
a doubly-linked list as-
The front node has a ‘Null’ value in the address part which shows the previous node’s
address.

A doubly-linked list allows us to traverse in both directions.

Circular linked list

It’s a type of linked list in which the very last node is connected to the first node, thus
forming a circular loop.

A circular linked list is one in which the end node carries a pointer to the list's initial node.

A circular linked list has no starting and ending node, and we can traverse both forward and
backward.
Applications
In web browsers

While moving through web pages, you have both options available - to either move to the
next page or the previous page. This is only possible because of a doubly linked list.

In music players

Similarly, we can switch to the next and the previous song in a music player using links
between songs. We can also play songs either from the starting or the end of the playlist.

In image viewer

The next and the previous photos are linked, and we can easily access them by using the
previous and next buttons.

In operating systems

The thread scheduler uses a doubly-linked list to maintain the list of all processes running at
any time. It enables us to move a certain process from one queue to another with ease.

In Multiplayer games

Online multiplayer games such as the likes of PUBG and Call of Duty use a circular linked
list to swap between players in a loop.

You might also like