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

Singly Link List

Uploaded by

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

Singly Link List

Uploaded by

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

Data Structures and Algorithms Made Easy Linked Lists

CHAPTER

LINKED LISTS
3
3.1 What is a Linked List?
static structures and therefore cannot be easily
One disadvantage of using arrays to store data is that arrays are maintain new insertions and deletions. In this
extended or reduced to fit the data set. Arrays are also expensive to
chapter we consider another data structure called Linked Lists that addresses some of the limitations of arrays.
data. A linked list has the following properties. A
A linked list is a data structre used for storing collections of
number of nodes in a list is not fixed and can grow and shrink
linked list is a linear dynamic data structure. The
- the data and a reference to the next node. The
on demand, Each node of a linked list is made up of two items
list is called the head of the list. It should be noted
last node has a reference to null. The entry point into a linked empty then the head is a null
the list is
that head is not a separate node, but the reference to the first node. If
reference.
Successive elements are connected by pointers.
The last element points to NULL.
Can grow or shrink in size during execution of a program.
Can be made just as long as required (until systems memory exhausts).
pointers). It allocates memory as list
Does not waste memory space (but takes some extra memory for
grows.
NULL

head

3.2 Linked Lists ADT


The following operations make linked lists an ADT:
Main Linked Lists Operations
Insert: inserts an element into the list
Delete: removes and returns the specified position element from the list
Auxiliary Linked Lists Operations
Delete List: remOves all elements of the list (disposes the list)
Count: returns the number of elements in the list
Find nth node from the end of the list

3.3 Why Linked Lists?


There are many other data structures that dothe same thing as linked lists. Before discussing linked lists it is
important to understand the difference between linked lists and arrays. Both linked lists and arrays are used to
store collections of data, and since both are used for the same purpose, we need to differentiate their usage. That
means in which cases arrays are suitable and in which cases linked lists are suitable.

3.4 Arrays Overview


One memory block is allocated for the entire array to hold the elements of the array. The array elements can be
accessed in constant time by using the index of the particular element as the subscript.
2 3
Index > 4 5

3.1 What is a Linked List? 43


Data Structures and Algorithms Made Easy Linked Lists
Why Constant
To access Time
an array element, Accessing
for the Array
address of Elements?
an element is computed as an offset from the base address of the array
and one multiplication is needed to compute what is supposed to be added to the base address to get the memory
calculated and then it is multnliy
an element of that data type is
address of the element, First the size of to be added to the base address. This process takes one multint: Wth
value neon
the index of the element to get theoperations take constant time, we can say the array access can be
and one addition, Since these two
in constant time.

Advantages of Arrays
Simple and easy to use
access)
Faster access to the elements (constant

Disadvantages of Arrays the array that are en


all needed memory up front and wastes memory space for indices in
Preallocates using it).
static (specify the array size before
Fixed size: The size of the array is array itself at the beginning, sometimes it mnay not be possible +
One block allocation: To allocate the (if big).
complete array the array size is
get the memory for the given position, we may need to shif %
position-based insertion: To insert an element at a desired position T
Complex for us to insert the new element at the operation is mor
existing elements. This will create a position
element is at the beginning, then the shifting
the position at which we want to add an
expensive.

DynamicArrays table, or array list) is a random accese


array, resizable array, dynamic
Dynamic array (also called as growable elements to be added or removed.
variable-size list data structure that allows
fixed size array. As soon as that
arrays is to initially start with someSimilarly,
One simple way of implementing dynamic reduce the array size
double the size of the original array.
array becomes full, create the new array
less than half.
half if the elements in the array are Hashing chapters.
dynamic arrays in the Stacks, Queues and
Note: We will see the implementation for
Advantages of Linked Lists
that they can be expanded
both advantages and disadvantages. The advantage of linked lists is of elements. To add more
Linked lists have memory for a certain number
in constant time. To create an arTay, we must allocate aray. This can
array into the new
create a new array and copy the old
elements to the array when full, we must
take a lot of time. than we need and waste
initially but then we might allocate more
We can prevent this by
allocating lots of space and add on new elements easily
linked list, we can start with space for just one allocated elemnent
memory. Witha reallocating.
without the need to do any copying and
Issues with Linked Lists (Disadvantages)The main disadvantage of linked lists is access time to individual
with linked lists. take
There are a number of issues element in the array. Linked lists
random-access, which means it takes O(1) to access any in access time is spacial
elements. Array is Another advantage of arrays
in the list in the worst case. element will be physically
O(n) for access to an element defined as contiguous blocks of memory, and so any array
locality in memory. Arrays are from modern CPU caching
methods.
greatly benefits can
near its neighbors. This with storing and retrieving data
allocation of storage is a great advantage, the overheadlast item is deleted, the last but one
Although the dynamic Sometimes linked lists are hard to manipulate. If the traversed to find the
make a big difference. This requires that the list is
changed to hold a NULL reference.
must then have its pointer pointer set to a NULL
reference.
but one link, and its
last reference points.
linked lists waste memory in terms of extra
Finally,
Arrays
Comparison of Linked Lists with Arrays and Dynamic suited to all circumstances, A
3.5 computer programming and design, no method is well
another. This is a list of some of
the
As with most choices in might work well n one case, but cause problems in dynamic collection. where elements
linked list data structure list structures. In general, if
you have a
common tradeoffs involving linked
44
Arrays and Dynamic Arravs
3.5 Comparison of Linked Lists with
Data Structures and Algorithms Made Easy Linked Lists

are frequently being added and deleted, and the location of new elements added to the list is significant, then
benefits of a linked list increase.
Parameter Linked list Array Dynamic array
Indexing O(n) O(1) O(1)
Insertion/deletion at Ofn), if array is not full (for shifting the O(n)
beginning O(1) elements)
O(1), if array is not
O(1), if array is not full full
Insertion at ending O(n) O(n), if array is full
Deletion at ending O(n) O(1) O()
Ofn), if array is not full (for shifting the O(n)
Insertion in middle O(n) elements)
O(n), if array is not full (for shifting the O(n)
Deletion in middle O(n) elements)
O(n) (for pointers) O
(n)
Wasted space

3.6 Singly Linked Lists We can think of each node as a record. The first part
The linked list consists of a series of structures called nodes. part of the record a feld that stores apointer to a
the second
of the record is a field that stores the data, and next field which is a pointer used to link one node to
node. So, each node contains two fields: a data field and a which
linked list. This list consists of a number of nodes in
the next node. Generally "linked list" means a singly the last node in the list is NULL, which indicates
The link of
each node has a next pointer to the following element.
the end of the list.
the node memory continues to exist until it is explicitly
Each node is allocated in the heap with a call to malloc(), so node in the list. The last node's next pointer
deallocated witha call to free). The node called a head is the first
points to NULL value.
40 NULL

Head

Following is a type declaration for a linked list of integers:


struct ListNode { //defines a ListNode in a linked list
int data; //the datum
struct ListNode *next; 1/pointer to the next ListNode

Basic Operations on a List


Traversing the list
Inserting an item in the list
Deleting an item fromn the list

Traversing the Linked List


the list we do the following,
the first node of the list. To traverse
Let us assume that the head points to
Follow the pointers. traversed.
count) as they are
Display the contents of the nodes (or
pointer points to NULL.
Stop when the next
4 + 1s 7E40 +NULL

head
The function given
function takes a linked list as input and counts the number of nodes in the list.
The length()
data with extra print function.
below can be used for printing the list
void print(struct ListNode *head) {
struct ListNode *cur - head; cur->next) {
for (cur = head; cur != NULL; cur =
printf"%d ", c°->data);
45
3.6 Singly Linked Lists
Data Structures and Algorithmns Made Easy
Linked List

printf("\n");
|/Calculating the size of the list
int length(struct ListNode *head) {
struct ListNode *cur = head;
int count =0;
for (cur =head: cur = NULL: cur = Cur->next) {
countt+;
cur = cur->next;

return count;

sizen. Space Complexity: O(1), for creating a temporary variabie


Tme Complexity:O(n), for scanning the list of
Singly Linked List Insertion
Insertion into a singly-linked list has three cases:
Inserting a new node before the head (at the beginning)
Inserting a new node after the tail (at the end of the list)
Inserting a new node at the middle of the list (random location) the
position p, assume that after inserting the elemnent
Note: To insert an element in the linked list at some
position of this new node is p.
Inserting a Node in Singly Linked List at the Beginning
one next pointer needs to be modified (new node's next pointer
In this case, a new node is inserted before the curent head node. Only
and it can be done in two steps:
Update the next pointer of new node, to point to the current head.
new node
data
4--15 40 NULL

Thead
Update head pointer to point to the new node.
new node
data 15 40 NULL
Thead
struet ListNode *insertAtBeginning(struct ListNode *head, int data){ //add to beginning of list
struct ListNode *temp;
1/ create a new temp node
temp-(struct ListNode *}malloc(sizeof(struct ListNode)); //create unnamed node and pointer
temp->data-data; //set temp data value
temp->next=NULL; //set as end of list
if (head= NULL){// then list empty, so set as head node
head-temp;
head->next=NULL;
else{// else add to left of list
temp->next-head;
head-temp;
return head:

Time Complexity: o(1). Space Complexity: O(1).


Inserting aNode in Singly Linked List at the Ending I
i
Tn this case, we need to modiy two
next pointers (last nodes next pointer and new S
nodes next pointer).
3.6 Singly Linked Lists 46
Data Structures and Algorithms Made Easy Linked Lists

New nodes next pointer points to NULL.


NULL
new node

4 15 data - ºNULL
head
Last nodes next pointer points to the new node. new node

- NULL
15
- data

head

struct ListNode *insertAtEnd(struct ListNode *head,int data) //add to end of list


struct ListNode *temp,*cr;
/create a new temp node
temp= (struct ListNode *)malloc(sizeof(struct ListNode): //create temp node
temp->data=data; //set temp value
temp->next-NULL; // set as end of list
*cur = head;
if (cur--NULL{
1/then no head node exists yet, so set temp as head
head=temp;
else{
/find end of c°rent list
while(cur->next NULL)
cur-cur->next;
I/c° is now the last node in list (next-NULL)
1/ set temp as new next node
cur->next =temp;
return head;
}
Time Complexity: O(n), for scanning the list of size n. Space Complexity: O(1).
Inserting a Node in Singly Linked List at the Given Position
Let us assume that we are given a position where we want to insert the new node. In this case also, we need to
modify two next pointers.
Toadd an element at position 3 then we stop at position 2. That means, traverse 2 nodes and insert the
new node. For simplicity let us assume that pred will point to the predecessor of new node. The next
pointer of new node points to the next node of the pred node.
pred node
4 15
70 NULL

new node
head
data

pred node's next pointer now points to the new node.


pred node
4 15
7 40 NULL

head
data
new node
Let us write the code for all three cases. We must update the first element pointer in the calling furnction, not just
n the called function. For this reason we need to send a double pointer. The following code inserts a node in the
singly linked list.
3.6 Singly Linked Lists 47
Data Structures and Algorithms Made Easy Linked Lists
1/Inserts a new node (ne) at position n and
struct ListNode *insertAtGivenPosition( structreturns
ListNodehead.
*head, struct ListNode *new, int n)?
1/pred will point to the predecessor of new
struct ListNode *pred = head;
1/Special case: adding at position 1 (nserting at head)
if ( n<= 1){
new -> next = head:
returm nevw;

17find the n-1 node (predecessor): decrement n and move down the list
1/until either the list has ended or n becomes 0
while ( --n && pred NULL )
pred = pred -> next; //repoint temp to the next element
if (pred == NULL )
return NULL;
7/ifit is not NULL, insert new after its predecessor
new -> next = pred -> next;
pred -> next = new;
return head;

Time Complexity: O(n). In the worst case, we may need to insert the iten at the end of the list. Space Complexity:
O(1).
Note: We can implement the three variations of the insert operation separately.
Time Complexity: O(n), since, in the worst case, we may need to insert the node at the end of the list. Space
Complexity: O(1).
Similar to insertion, here we also have three cases.
Deleting the frst node
Deleting the last node
Deleting an intermediate node.

Deleting the First Node in Singly Linked List


First node (current head node) is removed fom the list. It can be done in two steps:
Create a temporary node which will point to the same node as that of head.
4 15 7 40 NULL

Head Temp
Now, move the head nodes pointer to the next node and dispose of the temporary node.
15 40 NULL

Temp Head

void "deleteFirst(struct ListNode **head)


struct ListNode *temp;
if (*head = NULL)
return;
temp = *head:
*head (*head)->next;
free(temp);
return;

Time Complexity: O(n), for scanning the list of size n. Space Complexity: O(1).
Deleting the Last Node in Singly Linked List
In this case, the last node is removed rom the list. This operation is a bit trickier than removing the frst node,
becese the algoríthm should find a node, which is previous to the tail, It can be done in three stens:

3.6 Singly Linked Lists 48


Data Structures and Algorithms Made Easy Linked Lists

Traverse the list and while traversing maintain the previous node address also. By the time we reach the
end of the list, we will have two pointers, one pointing to the tail node and the other pointing to the node
before the tail node.

4 15 40 +NULL
Head
Node previous to tail Tail
Update previous node's next pointer with NULL.
NULL

4 15 7 40 NULL

Head
Previous node to tail Tail
Dispose of the tail node.
NULL

4 NULL

Head Previous node to tail Tail


void *deleteLast(struct ListNode **head)
struct ListNode *temp=NULL;
struct ListNode *current=*head:
if (*head == NULL)
return;
while(current->next){
temp = current;
Current = current->next:

temp->next = NULL;
free(current);
return;

Space Complexity: O(1).


Time Complexity: On), for scanning the list of size n.
Linked List
Deleting an Intermediate Node in Singly
located between two nodes. Head and tail
links are not updated in
always
In this case, the node to be removed is
removal can be done in two steps:
this case. Such a list. Once we find the node
Similar to the previous case, maintain the previous node while traversing thethe node to be deleted.
node's next pointer to thenext pointer of
to be deleted, change the previous

40 NULL
4 15

Node to be deleted
Head Previous node
deleted.
Dispose of the current node to be

40 NULL
15

Head Previous node Node to be deleted


position) {
void *delete (struct listNode **head,int
int k = 1;
struct listNode *p, *q;
if(*head == NULL){
printf ("List Empty");
return; 49
3.6 Singly Linked Lists
Data Structures and Algorithms Made Easy
Linked Lists
p=*head;
if(position == 1) /* from the beginning */
*head = (*head)->next;
free (p);
return;
else
while
k++;
(p I= NULL) 8&8% k< position ) (// traverse the list to the position from which we want to delete

p =p->next;

if(p == NULL{ /* at the end */


printf ("Position does not exist. \n");
return;
else /* from the middle */
q->next p->next;
free(p);
return:

Time Complexity: O(n). In the worst case, we may need to delete the node at the
Space Complexity: O(1). end of the list.

Deleting Singly Linked List


This works by storing the current node in some temporary
current node, go to the next node with a temporary variablevariable and freeing the current node. After freeing the
and repeat this process for all nodes.
void deleteLinkedList(struct ListNode **head){
struct ListNode
iterator = *head;*auxilaryNode, *iterator;
while (iterator) {
auxilary Node = iterator next;
free(iterator);
iterator= auxilaryNode;
*head NULL; / to affect the real head back in the
caller.
Time Complexity: O(n), for scanning the
complete list of size n. Space Complexity: O(1).
3.7 Doubly Linked Lists
A doubly linked list is a
the linked list in
whicha node contains a pointer to the
seguence.
data, a pointerTherefore, called two - way linked previous
in a doubly linked list (also as well as the
to the next node in list), a node consists ofnext node
node has two links: onepoint to the sequence (next pointer), a pointer to the previous node (previous three parts
one point to the next, or previous node, or points to a null value or empty list if pointer). bao
points to a null value or empty list if it is the final it is the first node, an
The advantage of a doubly linked list is node.
a singy linked list that given a node in the list, we can
we can delete a nodecannot
be removed unless we have navigate in both directions. A node 1
even if we don't have the previous the pointer to its predecessor. But ina doubly linked is
to the previous node and can move backward). node's address (since each node has a left
The primary disadvantages of doubly linked lists are:
pointer pointms
Each node requires an
The insertion or deletionextra pointer, requiring more space.
of a node takes a bit
ailar toa sngly linked list, let us longer (more pointer operations).
implement
inked list operations, then doubly inked list the operations of a doubly linked list. If vou understand the sing
linked list node: operations are obvious. Following is a type declaration for a douby
3.7 Doubly Linked Lists
50

You might also like