0% found this document useful (0 votes)
3 views61 pages

Lec 4

This document covers Lecture 4 of CS202 - Data Structures, focusing on linear data structures such as linked lists and stacks. It discusses the characteristics, advantages, and disadvantages of arrays and linked lists, including dynamic arrays and singly/doubly linked lists. Additionally, it highlights design decisions for a task management system and analyzes the time complexity of various operations on these data structures.

Uploaded by

afraz raza
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)
3 views61 pages

Lec 4

This document covers Lecture 4 of CS202 - Data Structures, focusing on linear data structures such as linked lists and stacks. It discusses the characteristics, advantages, and disadvantages of arrays and linked lists, including dynamic arrays and singly/doubly linked lists. Additionally, it highlights design decisions for a task management system and analyzes the time complexity of various operations on these data structures.

Uploaded by

afraz raza
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/ 61

CS202 – Data Structures

LECTURE-4

Linear Data Structures


Linked Lists and Stacks
Dr. Ihsan Ayub Qazi – Original Slide content
Register with “Poll Everywhere”
• Please register yourself using your LUMS email address:
https://pollev.com/blesseddawn004/register

• To participate in activities, please open the following link


on your browser and keep it open during class:
− https://pollev.com/blesseddawn004/

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Willington’s State of Project
Management Report, 2023
42% 82%
of projects fail of projects fail
when actions when actions take
are taken over 5 hours
within an hour

According to a Usability Engineering Lab


study, smooth drag-and-drop interactions
improve user satisfaction by 37% and
reduce task completion time by 20%.

A study by IEEE found that using B-Trees in a A Gartner report(2023) highlighted


real-time project management tool reduced that tools optimizing task filtering
database query latency by 25%, improving and sorting increased task
overall responsiveness for users. completion rates by 18%.
CS202: Data Structures Dr. Maryam Abdul Ghafoor Spring 2025 (LUMS)
Quick Recap
• We will be asking two questions in this course
− Does it work?
− Is it efficient?

• Asymptotic analysis for measuring the efficiency of


algorithms by providing a bound on the growth rate of
time as a function of input size

• ADT is mathematical model of data structure. List ADT is an


ordered collection of items.
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Agenda
• Dynamic Arrays
• Linked Lists
− How useful are Singly Linked Lists?
− How do Singly LLs compare with Doubly LLs?
− When would a Circular LL be more efficient than Singly LL or
Doubly LL?

• Stacks ADT

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
List ADT
Characterizing types of items

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Implementation Choices
• Arrays
• Linked lists

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Pros/Cons of Fixed Size Arrays (1/2)
• Pros
− O(1) indexing: Constant time access to an item given the index
− Space efficiency: Requires storing only the data items
• No additional space is required for pointers or other structural
metadata
• We’ll see that some structures require meta-data for maintenance
− Memory locality: Naturally derives benefit from data caches
• The spatial locality of contiguous data structures improves cache
utilization
• Processors can efficiently fetch and prefetch adjacent elements, leading
to faster execution and reduced memory access latency
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Pros/Cons of Fixed Size Arrays (2/2)
• Cons
− Pre-allocated size cannot be modified during execution
− Unused memory is wasted and inaccessible to other programs
− Program fails when data exceeds array capacity

• Real World Challenges


− Many apps require dynamic storage (social media posts,
streaming data)
− Even seemingly large allocations (e.g., 2³² or ~4 billion
addresses for IPv4) can become insufficient
− Size requirements often unknown at design time
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Enter Dynamic Arrays
• Dynamic arrays: Resizable array that grows by allocating
larger memory blocks during program execution

− Typical growth: Double size from m to 2m when full


− Contents copied to new array, old array deleted
− The primary thing lost using dynamic arrays is the guarantee
that each insertion takes constant time in the worst-case
• Even though the (amortized) average time for insertions is still
constant

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Implementation Choices
• Arrays
• Linked lists

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Linked List
• A linked list is made up of series of nodes, each with
− An associated item object
− A reference to the next node in the list
• A reference is address of the memory location
• A reference can provide more power then just copying the data
itself. E.g., library catalogue can be thought of the reference to the
shelf location of the book.

next next next


Item A Item B Item C null

• Traverse the list by following each node’s next reference.


CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Arrays vs Linked List
• Contiguous vs non-contiguous memory
• Single vs multi-data type
• Fixed vs dynamic sized
• Indexed vs sequential access
• Memory allocation compile vs run time

A B C D E F A 1 B 2 C 3 D null
0 1 2 3 4 5
array linked list

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Design Decisions Activity

You are hired to develop a task management system for a


project management software. The system manages tasks for
different teams in the company.

In the initial phase, the software allows users to:


− Add a task to the end of the team's task list.
− Remove completed tasks (at a specific index).
− View the task list sequentially.

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Design Decisions
Pros Cons

Arrays ● Fast Random Acccess ● Resizing overhead


● Memory Contiguity ● Costly deletion/insertion at
● Easy to add to end the front
● Because of indices, easy to ● Unused memory
shuffle
LinkedList ● Dynamic size ● Sequential Access
● Efficient insertions ● Cache unfriendliness
● No need to allocate extra ● Memory overhead
memory

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Singly Linked List

head
next next next
10 5 7 null

data

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Insertion in Linked List
next next next null
head 10 5 7

//You have access to the head pointer.


void List::insertAtHead(ListNode* newNode) {

// write your code here

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Linked List – Key Considerations
• Always think of corner cases first
− What if your list is empty?
− What if location is not reachable?
− etc

• Always draw a diagram!

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Concept Check! Poll

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Insertions at the End of a Singly Linked List

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Singly Linked List(SLL) Operations
Unsorted SLL
insertAtStart(int k) O(.)
insertAtLoc(int k, int loc) O(.)
insertAtEnd(int k) O(.)
deleteFromStart() O(.)
deleteFromLoc(int loc) O(.)
find(k) O(.)

Find the worst-case time complexity in terms of O(.)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Singly Linked List(SLL) Operations
Unsorted SLL
insertAtStart(int k) O(1)
insertAtLoc(int k, int loc) O(n)
insertAtEnd(int k) O(n)
deleteFromStart() O(1)
deleteFromLoc(int loc) O(n)
find(k) O(n)

Insertions at the end of the list are taking linear time

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Can we make insertions efficient?

CS202: Data Structures Dr. Maryam Abdul Ghafoor Spring 2025 (LUMS)
Insertions at the End of a Singly Linked List
tail

next next next null


head 10 5 13

next null
void List::insertAtEnd(int k) { 9

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Insertion at the End of a Singly Linked List
• Use tail pointer to keep track of the end of the linked list

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Deletion from the End of a Singly Linked List

Can we delete from the end of the singly linked


list more efficiently?

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of SLL Operations Poll
Which of the following describes the time complexity of the
insert(k), delete(k), deleteE() and find(k) in a sorted singly
linked list?
insert(k) θ(.)
delete(k) θ(.)
deleteE() θ(.)
Find(k) Θ(.)

Use the best possible algorithm (e.g., insertion at the beginning vs.
end) to find the time complexity in terms of θ.
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of SLL Operations Poll
Which of the following describes the time complexity of the
insert(k), delete(k), deleteE() and find(k) in a sorted singly
linked list?
insert(k) θ(n)
delete(k) θ(n)
deleteE() θ(n)
Find(k) Θ(n)

Use the best possible algorithm (e.g., insertion at the beginning vs.
end) to find the time complexity in terms of θ.
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Singly Linked List – Some Observations
• What is the time complexity (best case scenario)
− for inserting an element to the end? O(1)
− for inserting an element at the second-last position? O(n)

− for deleting an element form the end? O(n)


− for deleting an element from the second-last position? O(n)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Design Decisions Activity

• Now in phase-II, teams request the ability to:

− Add a task at any position (e.g., priority tasks at the start or


in the middle).
− Navigate forward and backward through tasks.
− Efficiently remove a specific task

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Doubly Linked List

head tail
next next next
null
null 10 5 7
prev prev prev
data
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Doubly Linked List(DLL) Operations
Unsorted DLL
insertAtStart(int k) O(.)
insertAtLoc(int k, int loc) O(.)
insertAtEnd(int k) O(.)
deleteFromStart() O(.)
deleteFromLoc(int loc) O(.)
find(k) O(.)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Doubly Linked List(DLL) Operations
Unsorted DLL
insertAtStart(int k) O(1)
insertAtLoc(int k, int loc) O(n)
insertAtEnd(int k) O(1)
deleteFromStart() O(1)
deleteFromLoc(int loc) O(n)
find(k) O(n)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Doubly Linked List(DLL) Operations
Sorted DLL
insert(int k) O(.)
delete(int k) O(.)
deleteFromStart() O(.)
deleteFromEnd() O(.)
find(k) O(.)

Find the worst-case time complexity in terms of O(.)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Doubly Linked List(DLL) Operations
Sorted DLL
insert(int k) O(n)
delete(int k) O(n)
deleteFromStart() O(1)
deleteFromEnd() O(1)
find(k) O(n)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Doubly Linked List – Some Observations
• What is the time complexity (best case scenario) for
− inserting an element to the end? O(1)
− inserting an element at the second-last position? O(1)

− deleting an element form the end? O(1)


− deleting an element from the second-last position? O(1)
− Searching an element? O(n)
− Inserting/deleting an element from kth location? O(n)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Practice! Activity
/* Suppose you have access to a function find(loc,
head) that returns a pointer to the node at location
loc, i.e., listNode* p = find(loc, head);
*/

void List::insert(int loc, listNode* newNode) {

//write code here

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Inserting in a DLL
void List::insert(int loc, listNode* newNode){
listNode* p = find(loc, head);

newNode->next = p;
newNode->prev = p->prev;
p->prev->next = newNode;

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Removing from a DLL Poll

void List::delete(int loc){


listNode* p = find(loc, head);
p->prev->next = p->prev;
p->next->prev = p->next;
delete p;
}

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Design Decisions Activity

In the last phase, the software adds a task rotation feature


for agile teams:
− Automatically assign the next task such that the last task links
back to the first (in a circular manner).
− Easily repeat tasks or navigate through the tasks list
indefinitely.

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Circular Linked List in Action

Multimedia applications use circular In multiplayer game, CLLs


linked lists for buffering, such as ensure that after the last player
audio/video streaming and data turn, it automatically loops
packet transmission in networking. back to the first player

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Circular Doubly Linked List
class ListNode { class List {
private: private:
int data; ListNode* head;
ListNode* next; int size;
ListNode* prev; public:
public: ... //similar to previously defined
ListNode():data(0),next(nullptr), prev(nullptr){} };
... //similar to previously defined
};

head

prev next next


10 5 7
prev prev next
data
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Circular Doubly Linked List(CDLL) Operations

Sorted CDLL
insert(int k) O(n)
delete(int k) O(n)
deleteFromStart() O(1)
deleteFromEnd() O(1)
find(k) O(n)

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Demo

CS202: Data Structures Dr. Maryam Abdul Ghafoor Spring 2025 (LUMS)
What’s so Good About Linked Lists?
Pros:
• Dynamic Size: A Linked List can grow or shrink dynamically.
• Non-contiguous memory: A linked list does NOT need
contiguous memory.
• Efficient insertions and deletions: Especially from the head
and/or tail of the list
• Efficient relocation of data: it is easier to move references than
the actual data items.
• Building blocks for complex data structure such as stacks,
queues, graphs etc.
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
What’s Not so Good About Linked Lists?
Cons:
• The references add overhead.
• Sequential access only, no direct access.
• Poor memory locality and cache performance
• The code to maintain a Linked List can be complex.

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Agenda
• Linked Lists
− How useful are Singly Linked Lists?
− How do Singly LLs compare with Doubly LLs?
− When would a Circular LL be more efficient than Singly LL or
Doubly LL?

• Stacks ADT

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack
• Objects are added and removed from the same end of the line.
− Value: collection of objects.
− Last book placed on the stack is first to take out of it.
• Stack Operations:
− Adding an element is called push operation push pop
− Removing an element is called pop operation
F
E
• a.k.a LIFO = Last In First Out structure D
C
B
A

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stacks Applications
• Applications
− Recursion – function call stack
− Expression evaluation
− Syntax Parsing in Compilers
− Undo/redo operations in software
− Browsers history

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack ADT

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Design Problem
• Which design approach will work best?

• Arrays or Linked list?

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack: Array implementation Poll
• How to implement efficiently a fixed-capacity stack with an
array?
least recently added
A. Stack: where last is first null
0 1 2 3 4 5

most recently added

B. first is last where Stack: null


0 1 2 3 4 5

C. Both A and B

D. Neither A nor B
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack: Array implementation
• Use array stack[] to store n items on stack.
• Push: add new item at stack[n].
• Pop: remove item from stack[n-1].
least recently added

Stack: where last is first null


Stack[6] 0 1 2 3 4 5

What will happen if n exceeds capacity?

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack Considerations
• Underflow. Throw exception if pop() called when stack is
empty.
• Overflow. Use “resizing array” for array implementation.

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack: Linked List Implementation
How to implement efficiently a stack with a singly linked list?
least recently added

A. Stack: where last is first null

most recently added

B. first is last where Stack: null

C. Both A and B

D. Neither A nor B
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Stack: Linked List Implementation
• Maintain pointer to first node in a singly linked list
• Push new element before first
• Pop item from first

most recently added

! first is last where Stack: null

first

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Stack Operations (Array)

Most Recently Most Recently


push pop push pop
added added
Item[0] 𝚹(.) 𝚹(.) Item[0] 𝚹(n) 𝚹(n)
item[n] 𝚹(.) 𝚹(.) item[n] 𝚹(1) 𝚹(1)

Assume that the array has enough space


and no resizing is required when
inserting an element

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Analysis of Stack Operations (Singly Linked List)

Most Recently Most Recently


push pop push pop
added added
First node 𝚹(.) 𝚹(.) First node 𝚹(1) 𝚹(1)
Last node 𝚹(.) 𝚹(.) Last node 𝚹(1) 𝚹(n)
Assume access to tail pointer

CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Practice Problems
• Given the head of a singly linked list, return the middle node of the
linked list. If there are two middle nodes, return the second
middle node.

• Given the head of a linked list, determine if the linked list has a cycle
in it.

• Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid. An input string is valid if:
− Open brackets must be closed by the same type of brackets.
− Open brackets must be closed in the correct order.
− Every close bracket has a corresponding open bracket of the same type.
CS202: Data Structures (Spring 2025) Dr. Maryam Abdul Ghafoor Adapted from Dr. Ihsan Ayub Qazi
Questions

CS202: Data Structures Dr. Maryam Abdul Ghafoor Spring 2025 (LUMS)

You might also like