0% found this document useful (0 votes)
10 views21 pages

Linked List 2

The document covers Abstract Data Types (ADT) focusing on Stacks and Queues, comparing Linked Lists and Arrays, and detailing their implementations and applications. It explains operations for adding and deleting elements, specifically in polynomial addition, and highlights the use of stacks for various applications like symbol matching and postfix expression evaluation. Additionally, it introduces Deques and outlines basic operations for both Queues and Stacks, concluding with a summary of topics to be covered in future lectures.

Uploaded by

Duy Võ
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)
10 views21 pages

Linked List 2

The document covers Abstract Data Types (ADT) focusing on Stacks and Queues, comparing Linked Lists and Arrays, and detailing their implementations and applications. It explains operations for adding and deleting elements, specifically in polynomial addition, and highlights the use of stacks for various applications like symbol matching and postfix expression evaluation. Additionally, it introduces Deques and outlines basic operations for both Queues and Stacks, concluding with a summary of topics to be covered in future lectures.

Uploaded by

Duy Võ
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/ 21

4/9/2024

Lecture 4
Abstract Data Types (ADT): Stacks,
and Queue
(Chapter 3 of textbook 1)

Single Linked List vs Array


Array Linked List
Pros Pros
Directly supported by C No need to determine size
Provides random access (index) Inserting and deleting elements is
quick
Cons Cons
Size determined at compile time No random access
Inserting and deleting elements is 1-way walking
time consuming Wasted space for pointer

Depending on the applications, we will use Linked List or Array

1
4/9/2024

Linked List application:


Polynomial ADT

Polynomial (2)
struct Node {
int coef;
int exp;
struct Node* next;
};

typedef struct Node* PtrToNode;


;

Two linked List are


already sorted by
exponent

2
4/9/2024

Addition of Two Polynomials


• Similar to merging two sorted lists
3x1200+10x50+15

p 3 10 15
1200 50 0

4x100+30x50+5

q 4 30 5
100 50 0
r

3 4 40 20
1200 100 50 0

PtrToNode add(PtrToNode poly1, PtrToNode poly2) {


PtrToNode result = NULL;
Quiz
while (poly1 != NULL && poly2 != NULL) {
Write C program for addition
if (poly1->exp of two
== poly2->exp) { polynomials
insert(result, poly1->coef + poly2->coef, poly1->exp);
poly1 = poly1->next;
poly2 = poly2->next;
} else if (poly1->exp > poly2->exp) {
insert(result, poly1->coef, poly1->exp);
poly1 = poly1->next;
} else {
insert(result, poly2->coef, poly2->exp);
poly2 = poly2->next;
}
}
while (poly1 != NULL) {
insert(result, poly1->coef, poly1->exp);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insert(result, poly2->coef, poly2->exp);
poly2 = poly2->next;
}
return result;
}

3
4/9/2024

Doubly Linked List


A node contains 2 pointers: to previous node and next node;

One can move in both directions;

2 3 11 7

NULL
NULL

Circular Linked List


The last node points to the first one. It can be done with
doubly lined list.

c d e f

4
4/9/2024

Examples of circular linked list


Registration problem:
An university with 2500 courses and 40000 students to generate two
types of reports: the list of students of each course and list of courses
of each student.
Solution 1: 2-D array=> 100 million entries=> bad idea
Solution 2: Multi-Lists

Multi Lists

Advantage:
Saving space
Disadvantage:
Expense of time

5
4/9/2024

Stack ADT
Stack is a list where you can access add or delete elements at one end.
Stacks are called ``last in first out’’ (LIFO), the last added
element among the current ones can be accessed or deleted.

Operations of Stack:

Stack CreateStack ()
int isEmpty (Stack S)
ElementType Pop (Stack S) -> Delete the element at top of a stack
void Push(Stack S, ElementType X) -> Add an element X at top of
a stack
ElementType Top(Stack S) -> Access the element at top of a stack

EXAMPLE

Push 5, 3, 1, Pop, Pop, Push 7

1
3 3
5 5 5
Push 3 Push 1
Push 5

Get 1 Get 3 7
3 5
5 5

Pop Pop Push 7

6
4/9/2024

Stack Implementation
Array

Need to know the maximum number of elements


Delete/Access/Add at the end
O(1) operation.

Store array length in the 0th position.


Delete/Access/Add at A[array length+1]

Example
Push 5, 3, 1, Pop, Pop, Push 7

1 5

2 5 3

3 5 3 1

2 5 3

1 5 25 7

7
4/9/2024

Linked List Implementation.

Need not know the maximum size

Add/Access/Delete in the beginning, O(1)

Push 5, 3, 1, Pop, Pop, Push 7

L Header 5 NULL

L Header 3 5 NULL

L Header 1 3 5 NULL

8
4/9/2024

L Header 3 5 NULL

L Header 5 NULL

L Header 7 5 NULL

Create a empty Stack with a


dummy header
void main() typedef struct Node {
ElementType element;
{ struct Node *Next;
};
Stack S = NULL; typedef struct Node* Stack
S = malloc (size of (struct Node));
S->Next = NULL;
}
S
Header NULL

9
4/9/2024

Basic operations of Stack


void Push(Stack S, ElementType X ) {
PtrToNode TmpCell;
TmpCell = malloc( sizeof( struct Node ) );
if( TmpCell == NULL ) FatalError( "Out of space!!!" );
else {
TmpCell->Element = X;
TmpCell->Next = S->Next;
int IsEmpty( Stack S ) {
S->Next = TmpCell;
return S->Next == NULL;
}
}
}

ElementType Pop( Stack S ) {


PtrToNode FirstCell; ElementType Top( Stack S ) {
ElementType X; if( !IsEmpty( S ) )
if( IsEmpty( S ) ) Error( "Empty stack" ); return S->Next->Element;
else { Error( "Empty stack" );
FirstCell = S->Next; return 0;
X = FirstCell->Element; }
S->Next = S->Next->Next;
free( FirstCell );
}
return X;
}

Stack Application

Function Calls

Decimal to Binary Conversion

Mathematical Expression
Symbol Matching
Evaluation of Postfix Expressions
Infix to Postfix Conversion

10
4/9/2024

Decimal to Binary Conversion


void outputInBinary(int n){
Stack s = new Stack
Quiz: Please
while write
(n > 0)a C program for Decimal to Binary
{
Conversion using Stack
int bit = n % 2
s.push(bit)
n = floor(n / 2)
}
while(s is not empty)
print(s.pop())
}

Example 2: Symbol Balancing


Braces, paranthenses, brackets, begin, ends
must match each other

[ { [ ( )] } ] => correct expression

[{]}() => wrong expression

Easy check using stacks

11
4/9/2024

Start from beginning of the file.


Push the beginning symbols you wish to
match, ignore the rest.
Push brace, parantheses, brackets, ignore the
alphabets
Whenever you encounter a right symbol, pop an
element from the stack. If stack is empty, then error.
Otherwise, if the popped element is the
corresponding left symbol, then fine, else there is an
error.
What is the complexity of the operation? O(n)

EXAMPLE
Check brace, bracket parentheses matching [a+b{1*2]9*1}+(2-1)

Push [, Push {, Pop, Pop, Push (, Pop

{
[ [

Push {
Push [

Oops! Something wrong,


Get { was expecting [

[
Pop Expect?

12
4/9/2024

EXAMPLE
Check brace, bracket parentheses matching [a+b{1*2}9*1]+(2-1)

Push [, Push {, Pop , Pop, Push (, Pop


Get {

{
[ [ [
Push { Pop
Push [ Perfect! Expect {

Get (
Get [
(
Pop Expect [ Push ( Pop Expect (

Symbol Priority
A*B + C
A*(B + C)
A+B+C*D
A*D+B+C*E

To do the correct operation, calculator needs to know the


priority of operands

We don’t need any priority nor parantheses if the operation is


expressed in postfix or reverse polish notion.

13
4/9/2024

Postfix
A*B + C = AB*C+

A*(B + C) = (B + C)*A = BC+A*

A+B+C*D = AB+CD*+

A*D+B+C*E = AD*B+CE*+

Suppose the expression is in postfix, how do we


compute the value?

Computation of a Postfix
Expression
Whenever you see a number push it in the stack.
Whenever you see an operator,
pop 2 numbers,
apply the operator,
Push the result
At end Pop to get answer

Complexity? O(n)

14
4/9/2024

EXAMPLE
Compute 5*4+6+7*2 Result: 40
Postfix: 5 4*6+7 2*+
Get 4

4
5 5 5
Push 4 Pop
Push 5

Get 5
6
20 20

Pop Push 20 Push 6

Get 6 Get 20

20 26

Pop Pop Push 26

Get 2
2
7 7 7
26 26 26
Push 7 Push 2 Pop
Get 7
Get 14
14 26
26
26 Pop
Push 14
Pop

15
4/9/2024

Get 26

40

Pop Push 40

Pop to get answer

Infix to Postfix Conversion


We can use a stack to convert an expression in standard form
(infix) into postfix.

We will concentrate on a small version of general problem by


allowing only the operators +, *, (,).

Example: a + b*c + ( d *e + f ) *g
 a b c * + d e * f +g * +

Implement Infix to Postfix conversion is your homework

16
4/9/2024

Queues ADT
List where an element is inserted at the end, and deleted
from the beginning. First in First out
Insertion and deletion at different ends. Deletion and
Insertion should be O(1)

Some terminologies:
Dequeue = Pop = Delete
Enqueue = Push = Insert
Head = Front
Tail = Rear

Basic operations of Queue

Queue CreateQueue ()
int isEmpty (Queue Q)
ElementType Dequeue (Queue Head) -> Delete the element at
head of a Queue (Deleting)
void Enqueue(Queue Tail, ElementType X) -> Add an element X at
tail of a Queue (Inserting)

17
4/9/2024

Linked List Implementation


Insert at the end of the linked list
Maintain a pointer to the last element. Whenever there is insertion, update
this ``last’’ pointer to point to the newly inserted element.

Delete from the beginning of the list

Both insertion and deletion are O(1)

Insert 5, 3, 1, Delete, Delete, Insert 7


Tail

Head Header 5 NULL

Tail

Head Header NULL


5 3

Tail

Head Header 5 3 1 NULL

18
4/9/2024

Tail

Head Header NULL


3 1

Tail

Head Header NULL


1

Tail

Head Header 1 7 NULL

Create a empty Queue with a


dummy header
struct queue {
PtrToNode Head;
PtrToNode Tail; Tail
};
typedef struct queue* Queue
Head
Queue CreateQueue(){ Header NULL

Queue Q = malloc(sizeof (struct queue));


Q->Head = malloc (sizeof (struct Node));
Q->Head->Next = NULL;
Q->Tail = Q->Head;
return Q;
}

19
4/9/2024

Basic operations of Queue


void Enqueue(Queue Q, ElementType X ) {
PtrToNode TmpCell;
TmpCell = malloc( sizeof( struct Node ) );
if( TmpCell == NULL ) printf( "Out of space!!!" );
else {
TmpCell->Element = X;
TmpCell->Next = Q->Tail->Next;
Q->Tail->Next = TmpCell;
Q->Tail = TmpCell;
}
}
ElementType Dequeue( Queue Q ) {
PtrToNode FirstCell;
ElementType X;
if( isEmpty( Q ) ) printf( "Empty stack" );
else {
FirstCell = Q->Head->Next;
X = FirstCell->Element;
Q->Head->Next = Q->Head->Next->Next;
free( FirstCell );
}
return X;
}

Deque ADT
A Deque is an abstract data structure which emphasizes specific
operations: Allows insertions and deletion at both the front and
back of the deque

Useful as a general-purpose tool: Can be used as either a queue or a


stack

Implement Deque as your homework

20
4/9/2024

Summary
• Doubly Linked List
• Circular Linked List
• Stack
• Queue, Deque
• Next week: Tree (chapter 4 of textbook 1)
• Please finish your homework

21

You might also like