0% found this document useful (0 votes)
76 views43 pages

13 Lists

This document discusses linked lists as an alternative to arrays for storing a sequence of data. It describes the basic structure of linked lists using nodes that contain a data field and a pointer to the next node. Functions for creating nodes and linking them are demonstrated. Key aspects like singly linked lists and the use of a head pointer are also covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views43 pages

13 Lists

This document discusses linked lists as an alternative to arrays for storing a sequence of data. It describes the basic structure of linked lists using nodes that contain a data field and a pointer to the next node. Functions for creating nodes and linking them are demonstrated. Key aspects like singly linked lists and the use of a head pointer are also covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

COL 100

Linked List
“All the kids who did great in high school writing pong games in
BASIC for their Apple II would get to college, take CompSci 101,
a data structures course, and when they hit the pointers
business their brains would just totally explode, and the next
thing you knew, they were majoring in Political Science because
law school seemed like a better idea.”

Joel Spolsky (launched Stack Overflow programmer Q&A site in


collaboration with Jeff Atwood)
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

List
• A list refers to a sequence of data items.

• Example: An array

• The array index is used for accessing and manipulation of array elements.
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Problems with Arrays


• The array size must be specified at compile time (for allocation on stack), or
before first use (for dynamic allocation)

• realloc can be used to readjust size in middle


• but contiguous chunk of memory may not be available and will require
copying the contents of the old block to the new block of memory.

• Deleting an element or inserting an element may require shifting of


elements

• Wasteful of space
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Linked List
• A completely different way to represent a list

• Make each data in the list part of a structure.

• The structure also contains a pointer or link to the structure (of the same
type) next data

• This type of list is called a linked list


structure 1 structure 2 structure 3

data data data


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Forming a linked list


• Let each structure of the list (lets call it node) have two fields:
1. First contains the data
2. Second holds the address of the next node/structure in the list

• The nodes/structures in the linked list need not be stored at contiguous


locations in the memory.

• They are ordered by logical links that are stored as part of the data in the
structure itself

• The link is a pointer to another structure of the same type


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Forming a linked list


• The pointer variable next contains either the struct node
address of the location in memory of the {
successor list element, or the special value int data;
NULL defined as 0. struct node *next;
}
• NULL is used to denote the end of the list (no
successor element)

• Such structures which contain a member field


pointing to the same structure type are called
self-referential structures.
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Writing Functions for Linked List


• When trying to write functions for Linked Lists draw pictures!
• If you don't draw pictures of what you are trying to do it is very easy to
make mistakes!
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: creating nodes


struct node struct node a, b, c;
{ a.data = 1;
int data; b.data = 2;
struct node *next; c.data = 3;
} a.next = b.next = c.next = NULL;

node a node b node c


1 NULL 2 NULL 3 NULL

data next data next data next


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: chaining nodes


struct node struct node a, b, c;
{ a.data = 1;
int data; b.data = 2;
struct node *next; c.data = 3;
} a.next = &b; b.next = &c;
c.next = NULL;

node a node b node c


1 2 3 NULL

data next data next data next


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Question?
• What are the values of:
• a.next->data
• a.next->next->data

node a node b node c


1 2 3 NULL

data next data next data next


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

“Singly” Linked List


• A singly “connected” linked list is a data structure
consisting of a sequence of nodes next
data

• Each node stores:


• data
• link to the next node

next next next


data data data NULL
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Singly Linked List: Head Pointer


• A head pointer addresses the first element of linked list
next
data

• Each element points at a successor element

• The last element has a link value NULL


head

next next next


data data data NULL
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Linked List: data


• In general, a node of the linked list may be represented as
Name of the
type of nodes
struct node_name
{
type member1; Data items in each
type member2; element of the list
......
struct node_name *next;
Link to the next
}
element in the list
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: list of student records


• Structure for each node
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};

• Suppose the list has three students’ records

• Declare three nodes n1, n2, and n3: struct stud n1, n2, n3;
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: list of student records


• Create the links between the nodes
struct stud
{ struct stud n1, n2, n3;
int roll;
char name[30]; n1.next = &n2 ;
int age; n2.next = &n3 ;
struct stud *next; n3.next = NULL ; /* No more nodes follow */
};

• The final list looks like


roll
name
age
next
n1 n2 n3
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example:
#include <stdio.h> /* Now traverse the list and print
struct stud { the elements */
int roll; p = head; /* point to head */
char name[30]; while (p != NULL)
int age; {
struct stud *next; printf(“\n %d %s %d”,
}; p->roll, p->name, p->age);
int main() { p = p->next;
struct stud n1, n2, n3; }
struct stud *p, *head; return 0;
scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); }
scanf (“%d %s %d”, &n2.roll, n2.name, &n2.age);
scanf (“%d %s %d”, &n3.roll, n3.name, &n3.age);
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;
head = &n1;
......
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Alternative Way
• Instead of statically declaring the structures n1, n2, n3, dynamically
allocate space for the nodes.

• Use malloc individually for every node allocated

• This is the usual way to work with linked lists


• number of elements in the list is usually not known in advance (if
known, we could have used arrays)
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: #include <stdio.h>


struct stud {
int roll; char name[30]; int age;
struct stud *next;
};
int main() {
struct stud *cur=NULL, *prev=NULL, *head=NULL;
int length = 0;
while(true) {
printf(“do you wish to enter more data\n”);
int choice; scanf(“%d”, &choice);
if(choice == 0) break;
++length;
cur = (struct node*)malloc(sizeof(struct node));
printf(“Enter data for student %d\n”, length);
scanf (“%d %s %d”, &cur->roll, &cur->name, &cur->age);
if(length == 1) head = cur;
else prev->next = cur;
prev = cur;
}
if(length != 0) cur->next = NULL;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Example: Working with the linked lists


• Assume that the list is already created and int main()
head points to the first element in the list {
struct node *head = NULL, *p;
:
:
• p is reused to point to the elements in the p = head;
list (initially, to the first element) while (p != NULL) {
printf(“%d “, p->data);
p = p->next;
}
• When p points to the last element, then we return 0;
have p->next=NULL, and the loop }
terminates after this iteration
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Important points to remember


• Always store the address of the first element added in a separate pointer
(head in our examples), and make sure not to change it.

• If you lose the start pointer, you cannot access any element in the list, as
elements are only accessible from the next pointers in the previous
element
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Important points to remember


• In the print example, we could have reused int main()
{
head=head->next instead of using a struct node *head = NULL, *p;
separate pointer p :
:
p = head;
• Not a good idea: we need to deallocate while (p != NULL) {
printf(“%d “, p->data);
the list also later (not shown for now) p = p->next;
}
return 0;
• Dellocating will require traversal again, }
deleting each node individually
• Remember: number of malloc calls
should always be equal to number of
free calls.
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Important points to remember


• In the print example, we could have reused int main()
{
head=head->next instead of using a struct node *head = NULL, *p;
separate pointer p :
:
p = head;
• Not a good idea: we need to deallocate while (p != NULL) {
printf(“%d “, p->data);
the list also later (not shown for now) struct node *q = p;
p = p->next;
free(q);
• Dellocating will require traversal again, }
deleting each node individually return 0;
}
• Remember: number of malloc calls
should always be equal to number of
free calls.
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Function to print a list


void display (struct node *head)
{
struct node *p = head;
printf(“List = {”);
while(p != NULL)
{
printf("%d, ", p->data);
p = p->next;
}
printf(“}\n”);
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Common Operations on Linked Lists


• Creating a linked list (already seen)
• Printing a linked list (already seen)

• Search for an element in a linked list


• Inserting an element in a linked list
• Insert at front of list
• Insert at end of list
• Insert in sorted order
• Delete an element from a linked list
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Search for an element in a linked list


• Traverses the list and compares value with each data
• Returns the node with the value if found, NULL otherwise

struct node* search(struct node *head, int value) {


struct node *p = r;
while (p != NULL) {
if (p->data == value)
return p;
p = p->next;
}
return p;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insertion in a list
• To insert a data item into a linked list involves
• creating a new node containing the data
• finding the correct place in the list, and
• linking in the new node at this place

• Correct place may vary depending on what is needed


• Front of list
• End of list
• Keep the list in sorted order
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insert in front of list


• Takes the head pointer and the value to be inserted
• Inserts the value as the first element of the list
• Returns the new head pointer value

struct node* insert(struct node *head, int value)


{
struct node *p;
p = (struct node *) malloc(sizeof(struct node));
p->data = value;
p->next = head;
return p;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insert in front of list head

18 3

head

15 18 3

head

15 18 3
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Using the insert function struct node* insert(struct node *head, int value) {
struct node *p;
p = (struct node *) malloc(sizeof(struct node));
p->data = value;
p->next = head;
return p;
void display(struct node*); }
struct node* insert(struct node *, int);
void display (struct node *head) {
struct node *p = head;
int main() { printf(“List = {”);
while(p != NULL) {
struct node *head = NULL; printf("%d, ", p->data);
p = p->next;
head = insert(head, 10); }
display(head); }
printf(“}\n”);

head = insert(head, 11);


display(head);
head = insert(head, 12); Output
display(head); List = {10, }
return 0;
} List = {11, 10, }
List = {12, 11, 10, }
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insert at end of linked list


• Takes the head pointer and the value to be inserted
• Inserts the value as the last element of the list
• Returns the new head pointer value
struct node* insert_end(struct node *head, int value) {
struct node* q = head;
while(q->next != NULL)
q = q->next; /* find the last element */
struct node* p = (struct node*) malloc(sizeof(struct node));
p->data = value; p->next = NULL;
q->next = p;
return head;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insert at end of list head

18 3

head

18 3 15

head

18 3 15
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Using insert at end function struct node* insert(struct node *head, int value) {
struct node *p;
p = (struct node *) malloc(sizeof(struct node));
struct node* insert_end(struct node *head, int value) { p->data = value;
struct node* q = head; p->next = head;
while(q->next != NULL) return p;
q = q->next; /* find the last element */ }
struct node* p = (struct node*) malloc(sizeof(struct node));
p->data = value; p->next = NULL;
q->next = p; void display (struct node *head) {
return head; struct node *p = head;
} printf(“List = {”);
while(p != NULL) {
printf("%d, ", p->data);
void display (struct node *); p = p->next;
struct node* insert(struct node*, int); }
printf(“}\n”);
struct node* insert_end(struct node*, int); }
int main() {
struct node *start = NULL;
start = insert_end(start, 10);
display(start); Output
start = insert_end(start, 11);
display(start);
List = {10, }
start = insert_end(start, 12); List = {10, 11 }
display(start);
return 0; List = {10, 11, 12, }
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insertion in the Middle: E.g., Ascending Order


head

3 5 8

7
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insertion in the Middle: E.g., Ascending Order


head

3 5 8

7
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insertion in the Ascending Order


• Create new node for the 7

• Find correct place – when pointer finds the 8 (7 < 8)

• Link in new node with previous (even if last) and pointer nodes

• Also check insertion before first node!


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Insertion in the Ascending Order


struct node* insert_asc(struct node* head, int value) {
struct node *cur, *prev, *new;
new = (struct node*) malloc(sizeof(struct node));
new->data = value; new->next = NULL;
cur = head; prev = cur;
while(cur != NULL) {
if (cur->data >= value) { /* insert before */
if (cur == head) {
new->next = head; /* insert at start */
return new;
}
new->next = cur; /* insert before p */
prev->next = new;
return head;
} if (head == NULL)
prev = cur; return new; /* first time */
cur = cur ->next; else
} /* exits loop if value > largest */ prev->next = new; /*insert at end*/
............ return head;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Deletion from a list


• To delete a data item from a linked list

• Find the data item in the list, and if found

• Delink this node from the list

• Free up the malloc’ed node space


Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Deletion from a list


head

3 5 7 8
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Deletion from a list


head

3 5 7 8

head

3 5 7 8
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Deletion from a list


head

3 5 7 8

head

3 5 7 8

head

3 5 8
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Deletion from a list


struct node* delete(struct node* head, int value) {
struct node *cur, *prev;
cur = head; prev = cur;
while(cur != NULL) {
if(cur->data == value) {
if(cur==head) head = cur->next;
else prev->next = cur->next;
free(cur);
return head;
} else {
prev = cur;
cur = cur->next;
}
}
return head;
}
Chetan Arora and Vireshwar Kumar COL 100: Introduction to Computer Science.
Department of Computer Science and Engineering, IIT Delhi Semester 1, 2023-24

Practice Excercises
• Print a list backwards (also try recursive Print here)

• Count the number of elements in a list (both using and not using recursion)

• Concatenate two lists

• Reverse a list

You might also like