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

5 - LinkedList - Data - Structure - V1

Uploaded by

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

5 - LinkedList - Data - Structure - V1

Uploaded by

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

Data Structure: Linked Lists

Tanvir Ahmed, PhD


Department of Computer Science,
University of Central Florida
Content
• Linked List
– Types of Linked List
– Linked Lists Operations
– Singly Linked List
• Traversing, Inserting, Deleting
• Sorted Linked List
– Doubly Linked List
• Traversing, Inserting, Deleting
• Sorted Linked List
– Circular linked list

Linked List 2
Linked List

Linked List 3
Linked List
• Sequence of connected nodes containing data
items.
• Each node contains a connection to another link
• Second most-used data structure after array
• Example representation of a Linked List:

Image source: https://www.tutorialspoint.com/data_structures_algorithms/linked_list_algorithms.htm

Linked List 4
Why linked list?
• Why not just use an array?
– Each node in an array is stored, physically, in contiguous spaces in
memory
– Arrays are fixed size (not dynamic)
– Inserting and deleting elements is difficult
– If you have an array of size 1000 and if we want to insert an element
after 5th element, all the remaining 995 items must be shifted.
• Why linked list?
– They are dynamic; length can increase and decrease as necessary.
– Each node does not necessarily follow the previous one in memory
– Insertion and deletion is cheap (only need to change few nodes at-
most)
• What is negative side of linked list?
– Getting a particular node may take a large number of operations, as
we do not know the address of any individual node

Linked List 5
Types of Linked List
• Simple/Singly Linked List - Item navigation is forward only

• Doubly Linked List – Items can be navigated forward and


backward.

• Circular Linked List - Last item contains link of the first


element as next and the first element has a link to the last
element as previous.

Linked List 6
Basic Operations of Linked Lists
• Insertion − Adds an element in the list.
• Deletion − Deletes a given item from the list.
• Display − Displays the complete list in a
forward manner.
• Search – Search for a given item

Linked List 7
Simple/Singly Linked List

Linked List 8
Defining a Node
info next
typedef struct node
{
Node int info;
struct node *next;
} node;

• A node has two parts:


– info or known as data, that holds the data you want to store
• You can store any type of data you want
– It can be simply an integer or multiple integer, or it can be a string, or it can be
even a structure
– How about you create a playlist? In that case you might want to store song name,
artist name, and more other information you want.

– and a link which is a pointer. Known as next. It is a pointer that can


point to a Node type variable
• i.e., it can hold address of a Node
Linked List 9
A node with more than one fields
struct Book_node
{
char name[20];
char author[8];
int year; struct Book
struct Book_node *next; {
}; char name[20];
char author[8];
int year;
• The above node has 3 };

fields for data struct Book_node


{
• The right side example, struct Book info;
has Book as data/info in struct Book_node *next;
};
the linked list’s node

Linked List 10
Head of the list

• The first node in the linked list is considered as head.


• A node type pointer is used to keep track of the head
• It is the most important node in a linked list.
• If you loss head some how in your code, you will loss
your linked list!
• What is an emptily linked list? NULL
– If head is NULL! head
Linked List 11
Traversing a Linked List
• While dealing with linked list, you have to walk through the linked list a lot.
• Traversing means: Traversing/ walking from Head to other nodes and accessing
them.
• Many operations require traversing
• Consider the following linked list. The following code snippet can give you an idea
how to traverse the list.

node *t;
• Can you think how to
t = head; //assuming Head already initialized display the info in
while (t->Next != Null)
the Linked List?
t = t->Next; • Just add the following
statement in the loop:
• Can you modify this code snippet to print printf (“%d ”, t->info);
only the even data? Linked List 12
Operations in a Linked List
• Insert a new node
• Delete a node
• Search for a node
• Counting nodes
• Modifying nodes
• and more

Linked List 13
Insert into Linked List
You can insert into 3 different places:
1. Beginning of the list
2. End of the list
3. Between nodes in the list
General Steps:
1. Create a temporary node. Fill the “data” and “next”
2. Look for position where to insert
3. Link the temporary node appropriately in the list

Special Caution:
Always deal with head specially as if you loss or mistake with
the head of the linked list, you will mess-up with your list!

Linked List 14
Coding linked list operations:
• In order to understand/write codes of linked list:
– it is best to draw example list and write code based on
the drawing
– During the lecture, we will draw and write line by line
codes in white board, so that we can process it and
relate them with the picture.
– In the slide, I have just provided the basic codes
without any comments due to space. However, they
will be explained during the lecture as mentioned
above.
– However, most of the codes with detailed comments
will be uploaded on webcourses.

Linked List 15
Inserting at the Beginning
• There can be many scenario when you might
need to insert the node in the front of the list.
– There can be two situations before insertion
• The list might be empty. How would you know?
– Who will be the head after insertion?
• Or there might be existing node(s) in the list.
– Who will be head now?
– Who will be after the head?
– Let’s see in the next slides

Linked List 16
Inserting at the Beginning
Start Node* insert_beginning(node *head, int
item)
Take input {
item node *t;
node *temp;
Create a temp new node temp=(node *) malloc( sizeof(node);
temp->info = item
temp->info=item;
Temp->next = NULL
temp->next=NULL;
if(head==NULL)
Is head head=temp;
No Null? Yes
else
{
temp->next = head head = temp temp->next = head;
head = temp;
}
head = temp return head;
}
Linked List 17
Inserting at the End
• There can be many scenario when you might
need to insert the node in the end of the list.
– There can be two situations before insertion
• The list might be empty. How would you know?
– Who will be the head after insertion?
• Or there might be existing node(s) in the list.
– Who will be head now?
– Who will be after the head?
– Let’s see in the next slides

Linked List 18
Inserting at the End
node* insert_end(node *head, int item)
Start {
node *t;
node *temp;
Take input
temp=(node *) malloc( sizeof(node);
item
temp->info=item;
Create a temp new node temp->next=NULL;
temp->info = item
Temp->next = NULL if(head==NULL)
head=temp;
else
Is head {
No Null? Yes t=head;
while(t->next!=NULL)
t = head;
Traverse until head = temp t=t->next;
t->next is Null t->next=temp;
}
return head;
t->next = temp
}
Linked List 19
#Now we will see a code example
to see how they are implemented

#The code is available in the


webcourses.
“SinglyLinkedListInsert_Delete.c”

Linked List 20
Inserting Between Nodes
• There can be many scenarios where you might need to insert the
node between nodes of the list.
• Example: Sorted linked list
• In this case, you might need to:
– Insert in the beginning or front (if the list is empty or the item is
smallest)
• We have seen how to deal with this
– Or at the end (the item is largest)
• We have seen how to deal with this
– Or between nodes
• Who will get affected by this operation?
• Remember:
– Still there can be case that your list might be empty:
• Who will be the head after insertion?
• Or there might be existing node(s) in the list.
– And always take care of your head with special conditions

Linked List 21
Inserting Between Nodes
• Use case: Sorted Linked List.
• Example of sorted linked list insertion:

a. Insert: 10 head 10 NULL

b. Insert: 2 head 2 10 NULL

c. Insert: 3 head 2 3 10 NULL

d. Insert: 11 head 2 3 10 11
NU
LL

• See from the above examples, there can be situations where you
might need to insert in the beginning, or to the end, or in between.
• But, all of these insertion is conditional!
– It means where to insert, it depends the item you are inserting, and the
items you already have in the linked list

Linked List 22
Inserting Between Nodes
a. Insert 10 head 10 NULL

b. Insert 2 head 2 10 NULL

c. Insert 3 head 2 3 10 NULL

NU
d. Insert 11 head 2 3 10 11 LL

• So, while inserting in a sorted linked list, we have to find a position for the
node we want to insert.
• As head is always special, can you guess at what scenario you will need to
insert the node in the head in the sorted linked list?
• There can be two situations to insert a node in the head:
– Either head is null (example a) or head’s item is greater than item (example b)
– See example a and b above.
– So, just translate it to code:
• If head == NULL or head->info >= item
– Insert in the beginning. (Example a and b above)
– You should already know how to insert in the beginning
Linked List 23
Inserting Between Nodes
a. Insert 10 head 10 NULL

b. Insert 2 head 2 10 NULL

c. Insert 3 head 2 3 10 NULL

NU
d. Insert 11 head 2 3 10 11 LL

• Now, if we find out that the item should not be inserted in the head, what would be the
next step?
• We need to traverse the linked list to find the appropriate place.
• Now, how long should we travers and how would you know that it is an appropriate place?
• There can be two reason to stop traversing:
1. Either you find out that you have reached to the end of the linked list, because none of the items
are bigger than the item you want to insert (example d above)
2. Or you find out a node that has larger info than your item (Example c above).
• For case 1, we will stop at the node with 10 (in example d) and then just join our temp
node after that. (linking 11 after 10)
• However, for case 2, we have to stop before the node with larger number as we
cannot come back if we jump there. So, we look ahead.
– For example, in example c, we have to stop at 2 so that we can join 3 after 2.
Linked List 24
Inserting Between Nodes
a. Insert 10 head 10 NULL

b. Insert 2 head 2 10 NULL

c. Insert 3 head 2 3 10 NULL

NU
d. Insert 11 head 2 3 10 11 LL

• So, for the scenario c and d above, the traversal will be like this:
t = head;
while (t->Next != NULL && t->next->info <item)
t = t->Next;
• Now after this loop, t stops exactly where we wanted it to stop:
– At 2 for inserting 3 ( example c)
– And at 10 when inserting 11 (example d)
• Now, how can we join our temp node after them?
• Temp->next will be t->next temp->next = t->next;
• And t-next will be temp t->next = temp
Linked List 25
Activity
Write SortedInsert(node* head,int item) function
Hints from previous slides

• If head is NULL or head->info >= item


– Insert in the beginning.
• How long should we traverse? Example c and d

t = head;
while (t->Next != NULL && t->next->info <item)
t = t->Next;

Insert temp after finding the position:


temp->next = t->next; //for last node, temp->next will be NULL
automatically as t->next was NULL
t->next = temp

Linked List 26
Activity
Write SortedInsert(int item) function
Hints from previous slides node* Sort_insert(node* head, int item)
{
• If head is NULL or head->info >= item Node *temp;
– Insert in the beginning. Node *t;
temp= (node *) malloc(sizeof(node));
• How long should we traverse? Example c and d temp->info=item;
temp->next=NULL;
t = head;
if (head==NULL || head->info >=item
while (t->Next != NULL && t->next->info <item) {
t = t->Next; temp->next = head;
head = temp;
Insert temp after finding the position: }
else
temp->next = t->next; {
t->next = temp t = head;
while (t->Next != NULL && t->next->info <item)
t = t->Next;

temp->Next = t->Next;
t->next = temp
}
return head;
}
Linked List 27
Delete operation
• You might need to delete a node :
– from the front of the list
– from the end of the list
– between nodes of the list
• In case of stack and queues that we will be
learning in next couple of lectures, they are by
default deleted from the head or tail due to their
nature
• However, most cases we would like to delete a
particular item from the list.
Linked List 28
Delete Operation
• Many cases you will want to delete a specific node by
searching.
– So: for deleting, you have to search the node containing
the item
– The node can be in the beginning, // how would you
know that your item is in the beginning?
• head->data == your item
– or in the end, // how would you know that?
• If the node you want to look for has the next as NULL.
– or in between nodes.
– While searching for the node, do not jump to the node
you want to delete while traversing.
• Because you want to delete it and how would you join the
previous node with the next one as you cannot go back?
– So, have a look to the data of next node before going there.

Linked List 29
Delete operation
• Deletes an item from the linked list
head 2 3 10 11 NULL

• Delete 2: temp = head;


head = head->next;
free(temp);
return head;
We have to check the
t = head;
reason of exiting the
while (t->next != NULL && t->next->info != item) loop.
t = t->next; If the loop exits for
• Delete 12: If(t->next == NULL ) return head; //item was not found t->next == NULL , then it
temp = t->next; indicates the item was
t->next = t->next->next; not found in the list
• Delete 3: free(temp)
return head;
Linked List

-In the above illustration, the colors used in the code are matched with the example in the left side
-Now write the function DelList(node* head, int item)
30
node* DelList(node* head, int item)
{
Full node *t;
Delete node *temp;
if(head==NULL)
Function return head;
if(head->info==item)
{
temp=head;
head=head->next;
free(temp);
return head;
}

t=head;
while(t->next!=NULL && t->next->info != item)
t=t->next;
if(t->next==NULL)
return head;
temp=t->next;
t->next=t->next->next;
free(temp);
return head;
}

Linked List 31
How would you implement Search
operation?

• Didn’t you search the item while deleting?


• Searching is just like traversing the linked list
until you find the item you are looking for (if
item exists) or until you reach to the end of the
linked list (not found).

Linked List 32
Doubly Linked List

Linked List 33
Doubly Linked List
• In case of singly linked list:
– Can you go back while traversing?
– What will happen if you write head = head->next?
• You can’t go back to the head
• In doubly linked list: you can go both forward and backward
• Application Scenario of doubly linked list:
• A music player which has next and prev buttons.
• The browser cache which allows you to hit the BACK-FORWARD
pages.
• Applications that have a Most Recently Used list (a linked list of
file names)
• Undo-Redo functionality
Linked List 34
Defining a Node

typedef struct nod


prev info next {
Node int info;
struct nod *prev, *next;
} node;

• Info holds the data


• Prev pointer is used to point to previous node
• Next pointer is used to point to the next node

Linked List 35
Inserting at the Beginning
Start node* insert_beg(node* head, int item)
{
Take input node *t;
item node *temp;
temp=(node *) malloc( sizeof(node);
Create a temp new node
temp->info = item temp->info=item;
Temp->prev = NULL temp->prev=NULL;
temp->next = head
temp->next=head;
if(head != NULL)
Is head
head->prev = temp;
No Null?
Yes head = temp;

return head;
}
head->prev = temp head = temp

Linked List 36
Inserting at the End
node *head;
Start node* insert_end(node *head, int item)
{
Take input node *t;
item node *temp;
temp=(node *) malloc( sizeof(node));
temp->info=item;
Create a temp new node temp->next=NULL;
temp->info = item if(head==NULL)
temp->next = NULL {
temp->prev = NULL;
head=temp;
}
Is head
else
No Null? Yes {
t=head;
t = head; temp->prev = NULL while(t->next!=NULL)
Traverse until head = temp t=t->next;
t->next is Null t->next=temp;
temp->prev = t;
t->next = temp }
return head;
temp->prev = t
Linked List
} 37
Inserting Between Nodes
• Like singly linked list, if you want to create a sorted
doubly linked list, you might need to insert it in the
beginning or end or between nodes.
– It requires extra management for prev pointer.
• As always create a new temp node and fill-up the
fields.
• Traverse where to insert
• Assign prev and next of the temp node based on t
and t->next
• Adjust next of t
• Adjust prev of t->next (if t->next is not NULL)
Linked List 38
Exercise
• Write the SortedInsert operation for Doubly
Linked List
– The hints already provided in previous slide
– Also take help from SortedInsert function of Singly
Linked List.

Linked List 39
node* DelListDoubly(node* head, int item)
{
Delete node *t;
node *temp;
operation if(head==NULL)
return head;//nothing to do
#similar to singly
if(head->info==item) {
linked list, with some temp=head;
additional condition head=head->next;
to adjust prev if (head != NULL) //new condition for doubly
head head -> prev = NULL;
2 3 free(temp);
10
return head;
}
t=head;
//traverse until reach to the end or find the item in next node.
Example of deleting while(t->next!=NULL && t->next->info != item)
15 (item does not t=t->next;
if(t->next==NULL)
exist)
return head; //not found, skip
temp=t->next;
t->next=t->next->next;
Deleting 3 or 10 if (t->next) //new condition for doubly
t->next->prev = t;
If you delete 10, this free(temp);
return head;
will be false as t-
} 40
>next is null. Linked List
Circular Linked List
• Circular Linked List - Last item contains link of the first
element as next and the first element has a link to the last
element as previous.
• Applicable for both singly and doubly linked list

• For a circular linked list:


– How would you know you are
Linked List in the end of the list?
– The last element should point to the head (instead of NULL)
41
Summary
• Linked List
• Linked List Operations
• Sorted Linked List
• Doubly linked list
• Circular linked list
• During the lecture we explained most of the
codes by scratching in papers.
– Scratching various situations would really help to
map them to code.

Linked List 42
Question?

Thank you ☺

Linked List 43

You might also like