Linked Lists
Linked Lists
1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Abstract Data Types
2
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Definition
An abstract data type (ADT) is a specification of a set of data and the set of
operations that can be performed on the set of data.
Such a data type is abstract in the sense that it is independent of various concrete
implementations.
• To perform some operation on the ADT, the user just calls a function.
• Details of how the ADT is implemented or how the functions are written is not
required to be known by the user.
• Even if the underlying implementations of the functions are changed, as long
as the function interfaces remain the same, the user can continue using the
ADT in the same way.
3
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example 1: List (a sequence of data items of the same type)
Create
Insert List
implementation
Delete and the
related functions
Traverse We shall later look into a concrete
way of implementing a list
A list is ordered: There are a first element, a second element, a third element, and so on.
4
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example 2 :: Set
union
intersection
difference
Set
insert
Note: A set is an
unordered collection.
delete
{1,2,3}, {1,3,2}, {2,1,3},
{2,3,1}, {3,1,2}, {3,2,1}
size are all the same set.
5
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example 2 :: Set
6
Example 3 :: Last-In-First-Out STACK
push
pop
create
STACK
isempty
isfull
7
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Visualization of a Stack
In Out
C B A B C
8
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example 3 :: Last-In-First-Out STACK
Assume:: stack contains integer elements
void push (stack s, int element);
/* Insert an element in the stack */
int pop (stack s);
/* Remove and return the top element */
void create (stack s);
/* Create a new stack */
int isempty (stack s);
/* Check if stack is empty */ We shall later look into a concrete
way of implementing a stack
int isfull (stack s);
/* Check if stack is full */
9
Example 4 :: First-In-First-Out QUEUE
enqueue
dequeue
create
QUEUE
isempty
size
10
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Visualization of a Queue
In Out
C B A B A
11
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example 4 :: First-In-First-Out QUEUE
Assume:: queue contains integer elements
void enqueue (queue q, int element);
/* Insert an element in the queue */
int dequeue (queue q);
/* Remove an element from the queue */
queue createq();
/* Create a new queue */
int isempty (queue q);
/* Check if queue is empty */ We shall later look into a concrete
way of implementing a queue
int size (queue q);
/* Return the no. of elements in queue */
12
Lists
13
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
List (an ordered sequence of data items of the same type)
Create
Insert List
implementation
Delete and the
related functions
Traverse
14
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Lists
• List is a sequence of data items (usually of the same type).
• Array – one way to represent a list.
• Advantages of arrays:
• Compact: no wastage of space
• Easy and constant time access given index of an element
We use a pointer inside a structure that points to a structure of the same type.
struct list {
int data;
struct list *next;
};
16
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Self-Referential Structures
struct list {
int data ;
struct list *next ;
} ;
17
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pictorial representation
struct list {
A structure of type struct list
int data ;
struct list *next ;
} ;
data next
NULL
18
struct list a, b, c;
a b c
1 NULL 2 NULL 3 NULL
data next data next data next
19
Chaining these together
a.next = &b;
b.next = &c;
a b c
1 2 3 NULL
data next data next data next
20
Linked Lists
A singly linked list is a concrete data
structure consisting of a sequence of nodes
next
Each node stores elem
• an element
• a link to the next node
node
A head pointer addresses the first element of the list.
Each element points at a successor element.
The last element has a link value NULL.
head
A B C D NULL
21
Header file : list.h
typedef char DATA;
// In this example, we store a char in each node; can be int, float, ...
struct list {
DATA d;
struct list * next;
};
typedef struct list ELEMENT;
Our own header file !!
typedef ELEMENT* LINK;
We can place this .h file in the same directory as
the .c source file, and include the header file as
#include “list.h”
22
Dynamic memory allocation: Review
typedef struct {
int hiTemp;
int loTemp;
double precip;
} WeatherData;
int main ( )
{
int numdays;
WeatherData *days;
scanf (“%d”, &numdays) ;
days=(WeatherData *)malloc(sizeof(WeatherData)*numdays);
if (days == NULL) printf (“Insufficient memory\n”);
...
free(days) ;
}
Storage allocation
LINK head ;
head = (LINK) malloc (sizeof(ELEMENT)); Recall:
head n NULL
24
Storage allocation
head->next = (LINK) malloc (sizeof(ELEMENT)); Recall:
head->next->d = ‘e’;
typedef struct list ELEMENT;
head->next->next = NULL; typedef ELEMENT* LINK;
head n e NULL
25
Storage allocation
head->next->next = (LINK) malloc (sizeof(ELEMENT));
head->next->next->d = ‘w’;
head->next->next->next = NULL; Recall:
head n e w NULL
26
Operations on Lists
28
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Produce a list from a string (each character in a node)
LINK StrToList (char s[ ]) { s H E L L O \0
LINK head = NULL, tail;
int i;
head H
if (s[0] != ‘\0’) {
head = (LINK) malloc (sizeof(ELEMENT));
head->d = s[0];
tail
tail = head;
for (i=1; s[i] != ‘\0’; i++) { head H
tail->next = (LINK) malloc(sizeof(ELEMENT));
tail = tail->next;
tail->d = s[i]; tail
}
tail->next = NULL;
head H E
}
return head;
} tail
Inserting a new element (node) into an existing linked list
30
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1. Allocate a new node
Inserting at the Head
2. Insert new element
3. Make new node point to old head
head X Y
4. Update head to point to new node
head X Y
head X Y 31
1. Allocate a new node
Inserting at the Tail
2. Insert new element
3. Have new node point to null
head X Y 4. Have old last node point to new node
NULL
5. Update tail to point to new node
tail
new = malloc(sizeof(ELEMENT));
new Z new->next = NULL;
NULL
Z tail->next = new;
head X Y
NULL
tail new
tail = new;
head X Y Z
NULL
tail 32
Create a new node containing the data
Insertion into a sorted list
Find the correct place in the list, and
newp N Link the new node at this place.
head A M P
newp = malloc(sizeof(ELEMENT));
prev ptr
head A M P
prev -> next = newp;
newp -> next = ptr;
prev ptr
newp N We will ensure that the pointer prev is
always one element behind pointer ptr.
The new node is to be inserted
between prev and ptr
Insertion into a sorted list: Implementation
struct list {
int data;
struct list *next;
}; Note: The Tail pointer is not maintained.
typedef struct list ELEMENT;
typedef ELEMENT *LINK;
36
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1. Update head to point to next node
Removing the first node in the list
2. Free the former first node
head X Y
ptr = head;
ptr
head = ptr->next;
X Y
ptr head
free(ptr);
X Y
ptr head 37
1. Bring ptr to the second last node
Removing the Tail (last node) 2. Make ptr->next equal to NULL
3. Free tail
4. Make ptr the new tail
head X Y Z
NULL
ptr tail
Z ptr->next = NULL;
head X Y
NULL NULL
ptr tail
free(tail);
head X Y Z tail = ptr;
NULL NULL
ptr tail 38
Steps:
Deletion from the middle of the list • Find the item (to be deleted) in the list
• Bring prev to the previous node
Item to delete: N • Link out node to be deleted, and
• Free up this node as free space.
head A M N P
head A M N P
prev ptr
What will happen if we did the following?
free(ptr);
prev->next = ptr->next;
39
Deletion function
// delete the item from a sorted list
LINK delete_item (int val, LINK ptr)
{
LINK prev, first;
42
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Searching for a data element in a linked list
43
Printing a linked list
44
Printing a linked list backwards
.
head
How can you print the elements of a list backwards when the links are in forward direction ?
45
Printing a linked list backwards – recursively
46
Counting the nodes in a linked list
47
Freeing all the nodes of a linked list
In each iteration temp1 points to the head of Recursive approach
the list and temp2 points at the second node.
void FreeAll ( ELEMENT *head )
void FreeAll ( ELEMENT *head ) {
if (head == NULL) return;
{
ELEMENT *temp1, *temp2; /* Recursively free the
temp1 = head; rest of the list */
FreeAll(head -> next);
while (temp1 != NULL) {
temp2 = temp1 -> next; /* Free the first node */
free(head);
free(temp1);
}
temp1 = temp2;
} What will happen if we free the first node of the list without placing a
pointer on the second?
}
What will happen if we traverse a freed linked list? 48
Practice Problems
1. Concatenate two lists (iteratively)
2. Reverse a list
3. Delete the maximum element from a list
4. Rotate the list by k positions counter-clockwise
For each of the above, first create the linked list by reading in integers from the keyboard and
inserting one by one to an empty list
Split a linked list of integers into two sublists as follows. The new lists must use the same nodes of
the original list, that is, do not malloc, but adjust the links only.
5. The two sublists are the first and the second halves of the original list.
6. The first sublist consists of the odd integers, and the second sublist the even integers of the
original list.
49
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR