5 Lists

Data Structures and Algorithms · Unit 5 · 8 hrs

Lists

Exam-focused notes for Lists (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 11 solved past questions from this unit.

Lists in short

This chapter studies the list as an abstract data type and its two concrete forms: the contiguous array list and the node based linked list, together with the singly, doubly and circular variants of the linked list and how a stack or queue can itself be built on top of one.

Lists: notes

Basic Concept, List and ADT, Array Implementation of Lists, Linked List

A list is a sequence of linearly ordered elements to which items can be added, removed or changed. As an abstract data type it supports operations such as get(p) (return the element at position p), insert(e, p) (insert element e at position p), remove(e) (remove the first occurrence of e), replace(e, p), size(), isEmpty() and isFull(). A list can be implemented in two ways: an array list (contiguous list), which stores elements in consecutive memory and accesses any element directly by index but must shift elements to insert or delete in the middle, and a linked list, which stores each element in its own node linked to the next.

Array implementation keeps an array arr[N] and an index last_index (initially $-1$) marking the last occupied cell. Inserting at position pos shifts every element from last_index down to pos one slot to the right to make room, then writes the new value at pos and increments last_index; deleting at pos shifts every element after pos one slot to the left and decrements last_index. Both operations cost $O(n)$ in the worst case, because of the shifting, even though reading arr[i] itself is $O(1)$.

A linked list removes the need for contiguous storage and for shifting: it is a collection of nodes, each holding an information part (the data) and a link part (the address of the next node); the link of the last node is NULL. Because each node is allocated separately with malloc, a linked list can grow or shrink at runtime and never needs to move existing elements to insert or delete, at the cost of using extra memory for the links and losing direct indexed access, since reaching the $k$-th node means following $k$ links, an $O(n)$ walk.

What this unit covers

  • Basic Concept, List and ADT, Array Implementation of Lists, Linked List
  • Types of Linked List: Singly Linked List, Doubly Linked List, Circular Linked List.
  • Basic operations in Linked List: Node Creation, Node Insertion and Deletion from Beginning, End and Specified Position
  • Stack and Queue as Linked List

Stack and Queue as Linked List

2081 · 10 marks

Define list. How can you use linked list to implement stack? Explain circular linked list.[10]

Show solved answer

List, Stack Using Linked List, and Circular Linked List


1. Definition of List

A list is a linear data structure that stores a collection of elements in a specific order. Each element in the list has a definite position (first, second, ..., last).

There are two main ways to implement a list:

  • Contiguous List (Array-based): A large enough array is defined to hold all items. The first item is placed at position 0, and successive items occupy successive positions. Insertion and deletion can be done anywhere within the list.
  • Linked List: Nodes are connected using pointers. Each node contains a data field (info) and a pointer field (next) that points to the next node. This is called a self-referential structure. The NULL value of the next field of the last node indicates the end of the list.

2. Implementing Stack Using Linked List

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The two primary operations are:

  • PUSH - Insert an element at the top
  • POP - Remove an element from the top

In a linked list implementation, the head (start) pointer acts as the TOP of the stack.

Node Structure

struct node {
    int info;
    struct node *next;
};
typedef struct node NodeType;
NodeType *top = NULL;

PUSH Operation (Insert at top)

Algorithm PUSH(item):
1. Create a new node:
       newnode = (NodeType*) malloc(sizeof(NodeType))
2. If newnode == NULL then
       Print "Stack Overflow"
       Return
3. Set newnode->info = item
4. Set newnode->next = top
5. Set top = newnode
6. End.

Diagram:

Before PUSH(30):    top -> [20] -> [10] -> NULL
After  PUSH(30):    top -> [30] -> [20] -> [10] -> NULL

POP Operation (Delete from top)

Algorithm POP():
1. If top == NULL then
       Print "Stack Underflow"
       Return
2. Set temp = top
3. Set item = temp->info
4. Set top = top->next
5. Free(temp)
6. Return item
7. End.

Diagram:

Before POP():    top -> [30] -> [20] -> [10] -> NULL
After  POP():    top -> [20] -> [10] -> NULL   (30 is returned)

Advantages of Linked List over Array for Stack

FeatureArray-based StackLinked List Stack
SizeFixed (static)Dynamic (grows/shrinks)
MemoryMay waste memoryUses only needed memory
OverflowPossibleOnly on memory exhaustion

3. Circular Linked List

Definition

A circular linked list is a list where the link field (next) of the last node points back to the very first node of the list, instead of pointing to NULL.

Circular linked lists can be used to help traverse the same list again and again if needed. A circular list is very similar to the linear list where the pointer of the last node points not to NULL but to the first node.

Diagram:

start
  |
  v
[10] -> [20] -> [30] -> [40]
  ^_______________________________|

C Representation

struct node {
    int info;
    struct node *next;
};
typedef struct node NodeType;
NodeType *start = NULL;
NodeType *last  = NULL;

Identifying the First Node

In a circular linked list, there are two methods to know if a node is the first node:

  1. An external pointer start (or list) points to the first node.
  2. A header node is placed as the first node of the circular list. The header node can be separated from others by:
    • Having a sentinel (dummy) value as the info part, OR
    • Having a dedicated flag variable to specify if the node is a header node.

Inserting a Node at the Beginning

Algorithm INSERT_BEGINNING(item):
1. newnode = (NodeType*) malloc(sizeof(NodeType))
2. If start == NULL then
       newnode->info = item
       newnode->next = newnode      // points to itself
       start = newnode
       last  = newnode
   End if
3. Else
       newnode->info  = item
       newnode->next  = start       // new node points to old first node
       start          = newnode     // update start to new node
       last->next     = newnode     // last node points to new first node
   End else
4. End.

Inserting a Node at the End

Algorithm INSERT_END(item):
1. newnode = (NodeType*) malloc(sizeof(NodeType))
2. If start == NULL then
       newnode->info = item
       newnode->next = newnode      // points to itself
       start = newnode
       last  = newnode
   End if
3. Else
       newnode->info  = item
       last->next     = newnode     // old last node points to new node
       last           = newnode     // update last pointer
       last->next     = start       // new last node points to start
   End else
4. End.

Advantages of Circular Linked List

  • Any node can be a starting point; the entire list can be traversed from any node.
  • Useful in round-robin scheduling, circular queues, and multiplayer games.
  • No need to check for NULL while traversing (stop when you reach the start again).

Summary Table:

FeatureLinear Linked ListCircular Linked List
Last node points toNULLFirst node
TraversalOne direction, stops at NULLCan loop continuously
Use caseGeneral lists, stacksRound-robin, circular queues
End detectionnext == NULLnext == start
Deleting the first nodeOnly start is updatedstart and last->next must both be updated
Reaching a node from any other nodeNot always possibleAlways possible

4. Conclusion

A list is an ordered collection of elements that can be held either contiguously in an array or as a chain of nodes joined by pointers. The linked representation is the natural one for a stack, because both PUSH and POP touch only the head of the chain and therefore run in O(1) time, while the stack grows and shrinks with the actual number of items instead of being limited by a fixed array size. A circular linked list changes only one pointer, the next of the last node, so that it addresses the first node, and that single change makes endless traversal from any starting node possible, which is why it is the structure behind round robin CPU scheduling and circular queues.

Open this answer on its own page →

2080 · 5 marks

How can you use linked list to implement stack? Explain. [5]

A stack can be implemented using a singly linked list where each node contains a data field and a pointer to the next node. The top pointer always points to the most recently inserted (top) node of the stack. Using a linked list overcomes the fixed-size limitation of array-based stacks. The stack...

Open this answer on its own page →

Basic operations in Linked List

2081 · 5 marks

What is the algorithm for node insertion and deletion from specified position from doubly linked list. [5]

Show solved answer

Node Insertion and Deletion at Specified Position in Doubly Linked List

Insertion at Specified Position in Doubly Linked List

In a doubly linked list, each node has three fields: prev, info, and next.

Algorithm

Algorithm: Insert a node at a specified position in a doubly linked list
Input: Position (pos), Data (val)

Steps:

  1. Create a new node and set newnode->info = val
  2. If head = NULL, then:
    • Set newnode->next = NULL
    • Set newnode->prev = NULL
    • Set head = newnode
    • Exit
  3. If pos = 1 (insert at beginning), then:
    • Set newnode->next = head
    • Set newnode->prev = NULL
    • Set head->prev = newnode
    • Set head = newnode
    • Exit
  4. Else, traverse to the specified position:
    • Set temp = head
    • Set count = 1
    • While count < pos - 1 and temp != NULL:
      • temp = temp->next
      • count = count + 1
    • End While
  5. If temp = NULL, then print "Position out of range" and Exit
  6. Set newnode->next = temp->next
  7. Set newnode->prev = temp
  8. If temp->next != NULL, then:
    • Set temp->next->prev = newnode
  9. Set temp->next = newnode
  10. End

Deletion at Specified Position in Doubly Linked List

Algorithm

Algorithm: Delete a node from a specified position in a doubly linked list
Input: Position (pos)

Steps:

  1. If head = NULL, then print "Empty list" and Exit
  2. Set temp = head
  3. If pos = 1 (delete from beginning), then:
    • Set hold = head
    • Set head = head->next
    • If head != NULL, then set head->prev = NULL
    • Free (hold)
    • Exit
  4. Else, traverse to the specified position:
    • Set count = 1
    • While count < pos and temp != NULL:
      • temp = temp->next
      • count = count + 1
    • End While
  5. If temp = NULL, then print "Position out of range" and Exit
  6. Set hold = temp
  7. If temp->prev != NULL, then:
    • Set temp->prev->next = temp->next
  8. If temp->next != NULL, then:
    • Set temp->next->prev = temp->prev
  9. Free (hold)
  10. End

Diagram Illustration

Before Insertion at position 2:

[NULL|10|-->]  <-->  [-->|20|-->]  <-->  [-->|30|NULL]

After Inserting 15 at position 2:

[NULL|10|-->] <--> [-->|15|-->] <--> [-->|20|-->] <--> [-->|30|NULL]

Key Point: In a doubly linked list, both the next pointer of the previous node and the prev pointer of the next node must be updated during insertion and deletion to maintain bidirectional linkage.

Open this answer on its own page →

2079 · 10 marks

How do you insert and delete a node at kth position of the doubly linked list? Describe the process of implementing stack and queue using linked list.[10]

--- A doubly linked list node has three fields: - prev -- pointer to previous node - info -- data field - next -- pointer to next node Step Action -------------- Step 1 Allocate memory for new node and assign data Step 2 If position is 1, insert at beginning and update head Step 3 Traverse to the...

Open this answer on its own page →

2075 · 5 marks

What are benifits of using linked list over array? How can you insert a node in a singly linked list? [5]

--- Feature Linked List Array --------- Size Dynamic, grows/shrinks at runtime Fixed size, declared at compile time Insertion/Deletion Efficient (no shifting needed) Requires shifting of elements Memory Allocates memory as needed May waste memory if unused Implementation Flexible for stacks, queu...

Open this answer on its own page →

Types of Linked List

2078 · 10 marks

Explain circular linked list with example. How do you implement linked list operation in singly linked list? Explain.[10]

--- A circular linked list is a linked list in which the last node does not contain a NULL pointer. Instead, the link field of the last node points back to the first node of the list, forming a circle or loop. Every node in the list has a successor, and there is no node with a NULL link. - INFO: ...

Open this answer on its own page →

2077 · 10 marks

Differentiate between singly linked list and doubly linked list. How do you insert and delete a node from doubly linked list? Explain.[10]

--- Feature Singly Linked List Doubly Linked List --------- Node Structure Each node has two fields: info (data) and next (pointer to next node) Each node has three fields: info (data), next (pointer to next node), and prev (pointer to previous node) Direction of Traversal Traversal is possible i...

Open this answer on its own page →

2074 · 10 marks

What do you mean by circular list? Differentiate between stack as a circular list and Queue as a circular list.[10]

A circular list is a linked list in which the last node points back to the first node, forming a closed loop or circle. Unlike a linear linked list where the last node points to NULL, in a circular list there is no NULL pointer -- every node has a successor. Key Properties: - The last node's next...

Open this answer on its own page →

2074 · 5 marks

What do you mean by double linked list? Explain with example. [5]

Show solved answer

Double Linked List

Definition

A doubly linked list (also called a two-way linked list) is a linked list in which every node contains three fields:

  1. PREV (Left Link) - a pointer that points to the previous node in the list
  2. INFO (Data) - the actual data stored in the node
  3. NEXT (Right Link) - a pointer that points to the next node in the list

The PREV pointer of the first node and the NEXT pointer of the last node both contain NULL.


Node Structure

+--------+--------+--------+
|  PREV  |  INFO  |  NEXT  |
+--------+--------+--------+

In C, the node can be declared as:

struct node {
    struct node *prev;
    int info;
    struct node *next;
};

Diagrammatic Example

Consider a doubly linked list containing three elements: 10, 20, 30

START
  |
  v
+------+----+------+    +------+----+------+    +------+----+------+
| NULL | 10 |  o---+--->|  o---| 20 |  o---+--->|  o---| 30 | NULL |
+------+----+------+    +------+----+------+    +------+----+------+
        Node 1      <---+---o        Node 2  <---+---o        Node 3
  • Node 1: PREV = NULL, INFO = 10, NEXT = address of Node 2
  • Node 2: PREV = address of Node 1, INFO = 20, NEXT = address of Node 3
  • Node 3: PREV = address of Node 2, INFO = 30, NEXT = NULL

Key Characteristics

FeatureDescription
TraversalCan be done in both forward and backward directions
PREV of first nodeAlways NULL
NEXT of last nodeAlways NULL
MemoryRequires more memory than singly linked list (extra pointer per node)

Advantages of Doubly Linked List

  1. Bidirectional traversal is possible (forward and backward).
  2. Deletion of a node is easier because we can access the previous node directly without traversing from the beginning.
  3. Insertion before a given node is simpler compared to singly linked list.

Disadvantage

  • Each node requires an extra pointer (PREV), which uses more memory than a singly linked list.

Summary

A doubly linked list allows movement in both directions through the list, making operations like reverse traversal, deletion, and insertion more efficient compared to a singly linked list, at the cost of slightly more memory per node.

Open this answer on its own page →

Basic Concept, List and ADT, Array Implementation of Lists, Linked List

2078 · 5 marks

Explain array implementation of list. [5]

An array implementation of a list (also called an ArrayList) is a method of implementing a linear list using a one-dimensional array as the underlying storage structure. Elements are stored in contiguous (sequential) memory locations, and a variable (commonly called size or count) keeps track of ...

Open this answer on its own page →

2077 · 5 marks

What is linked list? How is it different from array? [5]

A linked list is a linear data structure that defines a sequential set of elements (called nodes) in which each node stores two fields: 1. Info field - stores the actual data item 2. Link field - stores the pointer/address of the next node in the list The last node contains a NULL pointer, indica...

Open this answer on its own page →