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

4-ListStackQueue (2)

The document discusses linked lists, highlighting their structure, properties, and operations such as insertion, deletion, and traversal. It also covers stacks, explaining their LIFO nature, operations like push and pop, and implementation methods using arrays and linked lists. Additionally, it introduces postfix notation for arithmetic expressions and its advantages in computation.

Uploaded by

Omar Hamdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

4-ListStackQueue (2)

The document discusses linked lists, highlighting their structure, properties, and operations such as insertion, deletion, and traversal. It also covers stacks, explaining their LIFO nature, operations like push and pop, and implementation methods using arrays and linked lists. Additionally, it introduces postfix notation for arithmetic expressions and its advantages in computation.

Uploaded by

Omar Hamdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

Linked Lists

Chapter - 17
Introduction
• Data can be organized and processed
sequentially using an array, called a
sequential list
• Problems with an array
– Array size is fixed
– Unsorted array: searching for an item is slow
– Sorted array: insertion and deletion is slow

C++ Programming: Program Design Including Data Structures, Fifth Edition 2


Linked Lists
• Linked list: a list of items (nodes), in which
the order of the nodes is determined by
the address, called the link, stored in each
node

Link field in last node


is NULL
C++ Programming: Program Design Including Data Structures, Fifth Edition 3
Linked Lists
• Because each node of a linked list has two
components, we need to declare each
node as a class or struct
– Data type of a node depends on the specific
application
– The link component of each node is a pointer

C++ Programming: Program Design Including Data Structures, Fifth Edition 4


Linked Lists: Some Properties

C++ Programming: Program Design Including Data Structures, Fifth Edition 5


Linked Lists: Some Properties
• current = head;
– Copies value of head into current

C++ Programming: Program Design Including Data Structures, Fifth Edition 6


Linked Lists: Some Properties
• current = current->link;

C++ Programming: Program Design Including Data Structures, Fifth Edition 7


Traversing a Linked List
• The basic operations of a linked list are:
– Search to determine if an item is in the list
– Insert an item into the list
– Delete an item from the list
• Traversal: given a pointer to the first node
of the list, step through the nodes of the
list

C++ Programming: Program Design Including Data Structures, Fifth Edition 8


Traversing a Linked List
• To traverse a linked list:

• Example:

C++ Programming: Program Design Including Data Structures, Fifth Edition 9


Item Insertion and Deletion
• Consider the following definition of a node:

• We will use the following variable


declaration:

C++ Programming: Program Design Including Data Structures, Fifth Edition 10


Insertion
• Consider the following linked list:

• A new node with info 50 is to be created


and inserted after p

C++ Programming: Program Design Including Data Structures, Fifth Edition 11


Insertion

C++ Programming: Program Design Including Data Structures, Fifth Edition 12


Insertion
• Using two pointers, we can simplify the
insertion code somewhat

• To insert newNode between p and q:


The order in which these statements
execute does not matter

C++ Programming: Program Design Including Data Structures, Fifth Edition 13


Insertion

C++ Programming: Program Design Including Data Structures, Fifth Edition 14


Deletion

Node with info 34 is removed from the list, but


memory is still occupied; node is dangling
C++ Programming: Program Design Including Data Structures, Fifth Edition 15
Deletion

C++ Programming: Program Design Including Data Structures, Fifth Edition 16


Building a Linked List
• If data is unsorted
– The list will be unsorted
• Can build a linked list forward or backward
– Forward: a new node is always inserted at the
end of the linked list
– Backward: a new node is always inserted at
the beginning of the list

C++ Programming: Program Design Including Data Structures, Fifth Edition 17


Building a Linked List Forward
• You need three pointers to build the list:
– One to point to the first node in the list, which
cannot be moved
– One to point to the last node in the list
– One to create the new node

C++ Programming: Program Design Including Data Structures, Fifth Edition 18


Building a Linked List Forward

C++ Programming: Program Design Including Data Structures, Fifth Edition 19


Building a Linked List Forward

C++ Programming: Program Design Including Data Structures, Fifth Edition 20


Building a Linked List Forward

We now repeat statements three more times:

C++ Programming: Program Design Including Data Structures, Fifth Edition 21


Building a Linked List Backward
• The algorithm is:
– Initialize first to NULL
– For each item in the list
• Create the new node, newNode
• Store the item in newNode
• Insert newNode before first
• Update the value of the pointer first

C++ Programming: Program Design Including Data Structures, Fifth Edition 22


Search the List
• Steps:
– Compare the search item with the current
node in the list
• If the info of the current node is the same as the
search item, stop the search
• Otherwise, let the next node be the current node
– Repeat Step 1 until the item is found
• Or, until no more data is left in the list to compare
with the search item

C++ Programming: Program Design Including Data Structures, Fifth Edition 23


Delete a Node
• Case 1: List is empty
– If the list is empty, output an error message
• Case 2: List is not empty
– The node to be deleted is the first node
– First scenario: List has only one node

C++ Programming: Program Design Including Data Structures, Fifth Edition 24


Delete a Node
– Second scenario: List of more than one node

C++ Programming: Program Design Including Data Structures, Fifth Edition 25


Delete a Node
• Case 3: Node to be deleted is not the first
one
– Case 3a: Node to be deleted is not last one
– Case 3b: Node to be deleted is the last node

C++ Programming: Program Design Including Data Structures, Fifth Edition 26


Delete a Node
• Case 4: Node to be deleted is not in the
list
– The list requires no adjustment
– Simply output an error message

C++ Programming: Program Design Including Data Structures, Fifth Edition 27


Doubly Linked Lists
• Doubly linked list: every node has next
and back pointers

• Can be traversed in either direction

C++ Programming: Program Design Including Data Structures, Fifth Edition 28


Doubly Linked Lists
• Operations:
– Initialize the list
– Destroy the list
– Determine whether the list is empty
– Search the list for a given item
– Retrieve the first element of the list
– Retrieve the last element of the list

C++ Programming: Program Design Including Data Structures, Fifth Edition 29


Doubly Linked Lists
– Insert an item in the list
– Delete an item from the list
– Find the length of the list
– Print the list
– Make a copy of the doubly linked list

C++ Programming: Program Design Including Data Structures, Fifth Edition 30


Insert a Node
• There are four cases:
– Case 1: Insertion in an empty list
– Case 2: Insertion at the beginning of a nonempty
list
– Case 3: Insertion at the end of a nonempty list
– Case 4: Insertion somewhere in nonempty list
• Cases 1 and 2 require us to change the value
of the pointer first
• Cases 3 and 4 are similar (after inserting an
item, count is incremented by 1)

C++ Programming: Program Design Including Data Structures, Fifth Edition 31


Delete a Node
• Case 1: The list is empty
• Case 2: The item to be deleted is in the first
node of the list, which would require us to
change the value of the pointer first
• Case 3: Item to be deleted is somewhere in the
list
• Case 4: Item to be deleted is not in the list
• After deleting a node, count is decremented by
1

C++ Programming: Program Design Including Data Structures, Fifth Edition 32


Circular Linked Lists
• Circular linked list: a linked list in which the
last node points to the first node

C++ Programming: Program Design Including Data Structures, Fifth Edition 33


Circular Linked Lists
• Operations on a circular list are:
– Initialize the list (to an empty state)
– Determine if the list is empty
– Destroy the list
– Print the list
– Find the length of the list
– Search the list for a given item
– Insert an item in the list
– Delete an item from the list
– Copy the list
C++ Programming: Program Design Including Data Structures, Fifth Edition 34
#include <iostream>
using namespace std;
//Declare Node
struct Node{
int num;
Node *next;
};

//Declare starting (Head) node


struct Node *head=NULL;

//Insert node at start


void insertNode(int n)
{
struct Node *newNode=new Node;
newNode->num=n;
newNode->next=head;
head=newNode;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 35


//Traverse/ display all nodes (print items)
void display()
{
if(head==NULL)
{
cout<<"List is empty!"<<endl;
return;
}
struct Node *temp=head;
while(temp!=NULL)
{
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 36


//delete node from start
void deleteItem()
{
if(head==NULL)
{
cout<<"List is empty!"<<endl;
return;
}
cout<<head->num<<" is removed."<<endl;
head=head->next;
}
int main(){
display();
insertNode(10);
insertNode(20);
insertNode(30);
insertNode(40);
insertNode(50);
display();
deleteItem(); deleteItem(); deleteItem(); deleteItem();
deleteItem();deleteItem();display();
system("pause");
return 0;
}C++ Programming: Program Design Including Data Structures, Fifth Edition 37
Stacks and Queues

Chapter - 18
Stacks
• Stack: list of homogenous elements
– Addition and deletion occur only at one end,
called the top of the stack
• Example: in a cafeteria, the second tray can be
removed only if first tray has been removed
– Last in first out (LIFO) data structure
• Operations:
– Push: to add an element onto the stack
– Pop: to remove an element from the stack

C++ Programming: Program Design Including Data Structures, Fifth Edition 39


Stacks (cont’d.)

C++ Programming: Program Design Including Data Structures, Fifth Edition 40


Stacks (cont’d.)

Peek () Same as pop, but does not remove the element.

C++ Programming: Program Design Including Data Structures, Fifth Edition 41


– Stack is said to be in Overflow state when it is
completely full.

– Stack is said to be in Underflow state if it is


completely empty.

C++ Programming: Program Design Including Data Structures, Fifth Edition 42


Algorithm for PUSH operation
– Check if the stack is full or not.

– If the stack is full, then print error of overflow


and exit the program.

– If the stack is not full, then increment the top


and add the element.

43
Algorithm for POP operation
– Check if the stack is empty or not.
– If the stack is empty, then print error of
underflow and exit the program.
– If the stack is not empty, then print the
element at the top and decrement the top.

C++ Programming: Program Design Including Data Structures, Fifth Edition 44


Implementation of Stacks as
Arrays
– First element can go in first array position, the
second in the second position, etc.
– The top of the stack is the index of the last
element added to the stack
– Stack elements are stored in an array
– Stack element is accessed only through top
– To keep track of the top position, use a
variable called stackTop

C++ Programming: Program Design Including Data Structures, Fifth Edition 45


Implementation of Stacks as Arrays
• Because stack is homogeneous
– You can use an array to implement a stack

• Can dynamically allocate array


– Enables user to specify size of the array

C++ Programming: Program Design Including Data Structures, Fifth Edition 46


Implementation of Stacks as Arrays
• C++ arrays begin with the index 0
– Must distinguish between:
• The value of stackTop
• The array position indicated by stackTop
• If stackTop is -1, the stack is empty
• If stackTop is nonzero, the stack is not
empty
– The top element is given by stackTop

C++ Programming: Program Design Including Data Structures, Fifth Edition 47


#include <iostream>
using namespace std;
#define max_size 101
int A[max_size];
int top=-1;
void push(int x)
{
if(top==max_size-1)
{
cout<<"overflow"<<endl;
return;
}
A[++top]=x;
}
void pop()
{
if(top==-1)
{
cout<<"no elements to pop"<<endl;
return;
}
top--;
}
int Top()
{
return A[top];
}
bool IsEmpty()
{
if(top==-1)
return true;
else
return false;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 48


void print()
{
int i;
cout<<"Stack: ";
for(i=0;i<=top;i++)
cout<<A[i]<<" ";
cout<<endl;
}
int main ()
{
push(2);
print();
push(5);
print();
push(7);
print();
pop();
print();
system("pause");
return 0;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 49


Linked Implementation of
Stacks
• Array only allows fixed number of
elements
• If number of elements to be pushed
exceeds array size
– Program may terminate
• Linked lists can dynamically organize data
• In a linked representation, stackTop is
pointer to top element in stack

C++ Programming: Program Design Including Data Structures, Fifth Edition 50


Linked Implementation of
Stacks

C++ Programming: Program Design Including Data Structures, Fifth Edition 51


Push
• The newElement is added at the beginning of
the linked list pointed to by stackTop

C++ Programming: Program Design Including Data Structures, Fifth Edition 52


Push

C++ Programming: Program Design Including Data Structures, Fifth Edition 53


Pop
• Node pointed to by stackTop is removed

C++ Programming: Program Design Including Data Structures, Fifth Edition 54


Pop

C++ Programming: Program Design Including Data Structures, Fifth Edition 55


Application of Stacks: Postfix
Expressions Calculator
• Infix notation: usual notation for writing
arithmetic expressions
– The operator is written between the operands
– Example: a + b
– The operators have precedence
• Parentheses can be used to override precedence

C++ Programming: Program Design Including Data Structures, Fifth Edition 56


Application of Stacks: Postfix
Expressions Calculator
• Prefix (Polish) notation: the operators are
written before the operands
– Introduced by the Polish mathematician Jan
Lukasiewicz
• Early 1920s
– The parentheses can be omitted
– Example: + a b

C++ Programming: Program Design Including Data Structures, Fifth Edition 57


Application of Stacks: Postfix
Expressions Calculator
• Reverse Polish notation: the operators
follow the operands (postfix operators)
– Proposed by the Australian philosopher and
early computer scientist Charles L. Hamblin
• Late 1950's
– Advantage: the operators appear in the order
required for computation
– Example: a + b * c
• In a postfix expression: a b c * +

C++ Programming: Program Design Including Data Structures, Fifth Edition 58


Application of Stacks: Postfix
Expressions Calculator

C++ Programming: Program Design Including Data Structures, Fifth Edition 59


Application of Stacks: Postfix
Expressions Calculator
• Postfix notation has important applications
in computer science
– Many compilers first translate arithmetic
expressions into postfix notation and then
translate this expression into machine code
• Evaluation algorithm:
– Scan expression from left to right
– When an operator is found, back up to get the
operands, perform the operation, and
continue
C++ Programming: Program Design Including Data Structures, Fifth Edition 60
Application of Stacks: Postfix
Expressions Calculator
• Example: 6 3 + 2 * =

C++ Programming: Program Design Including Data Structures, Fifth Edition 61


Queues
• Queue: Like stack, queue is also an
ordered list of elements of similar data
types.
• Elements are:
– Added at one end (the back or rear)
– Deleted from the other end (the front or head)
• First In First Out (FIFO) data structure
– Middle elements are inaccessible
• Example:
– Waiting line in a bank
62
• The process to add an element into queue
is called Enqueue and the process of
removal of an element from queue is
called Dequeue.
• peek( ) function is often used to return the
value of first element without de-queuing
it.

63
Applications of Queue
• Serving requests on a single shared resource,
like a printer, CPU task scheduling etc.

• In real life scenario, Call Center phone systems


uses Queues to hold people calling them in an
order, until a service representative is free.

• Handling of interrupts in real-time systems. The


interrupts are handled in the same order as they
arrive i.e. First come first served.

64
Queue Implementation
• Queue can be implemented using an Array, or
Linked List. The easiest way of implementing a
queue is by using an Array.

• Initially the head (FRONT) and the tail (REAR) of


the queue points at the first index of the array
(starting the index of array from 0). As we add
elements to the queue, the tail keeps on moving
ahead, always pointing to the position where the
next element will be inserted, while
the head remains at the first index.

65
66
• When we remove an element from Queue, we
can follow two possible approaches (mentioned
[A] and [B] in above diagram). In [A] approach,
we remove the element at head position, and
then one by one shift all the other elements in
forward position.

• In approach [B] we remove the element


from head position and then move head to the
next position.

67
• In approach [A] there is an overhead of shifting
the elements one position forward every time we
remove the first element.

• In approach [B] there is no such overhead, but


whenever we move head one position ahead,
after removal of first element, the size on Queue
is reduced by one space each time.

C++ Programming: Program Design Including Data Structures, Fifth Edition 68


Algorithm for ENQUEUE operation
• Check if the queue is full or not.
• If the queue is full, then print overflow error and
exit the program.
• If the queue is not full, then increment the tail
and add the element.
Algorithm for DEQUEUE operation
• Check if the queue is empty or not.
• If the queue is empty, then print underflow error
and exit the program.
• If the queue is not empty, then print the element
at the head and increment the head.
69
/* Below program is written in C++ language for linear
Q */
#include<iostream>
using namespace std;
#define SIZE 10
class Queue
{
int a[SIZE];
int rear; //same as tail
int front; //same as head
public:
Queue()
{
rear = front = -1;
}
//declaring enqueue, dequeue and display
functions
void enqueue(int x);
int dequeue();
void display();
};

C++ Programming: Program Design Including Data Structures, Fifth Edition 70


// function enqueue - to add data to queue
void Queue :: enqueue(int x)
{
if(front == -1) {
front++;
}
if( rear == SIZE-1)
{
cout << "Queue is full";
}
else
{
a[++rear] = x;
}
}

// function dequeue - to remove data from queue


int Queue :: dequeue()
{
return a[++front]; // following approach [B], explained above
}
// function to display the queue elements

C++ Programming: Program Design Including Data Structures, Fifth Edition 71


// function to display the queue elements
void Queue :: display()
{ int i;
cout<<"data in queue:";
for( i = front; i <= rear; i++)
{
cout <<a[i]<<" ";
}
cout<<endl;
}
int main() //// the main function
{
Queue q;
q.enqueue(10);
q.display();
q.enqueue(100);
q.display();
q.enqueue(1000);
q.display();
q.enqueue(1001);
q.display();
q.enqueue(1002);
q.display();
q.dequeue();
q.display();
q.enqueue(1003);
q.display();
q.dequeue();
q.display();
q.dequeue();
q.display();
system("pause");
return 0;
}
C++ Programming: Program Design Including Data Structures, Fifth Edition 72
What is a Circular Queue?

• Before we start to learn about Circular queue,


we should first understand, why we need a
circular queue, when we already have
linear queue data structure.
• In a Linear queue, once the queue is completely
full, it is not possible to insert more elements.
Even if we dequeue the queue to remove some
of the elements, until the queue is reset, no new
elements can be inserted. You must be
wondering why?
73
• When we dequeue any element to remove
it from the queue, we are actually moving
the front of the queue forward, thereby
reducing the overall size of the queue. In
addition, we cannot insert new elements,
because the rear pointer is still at the end
of the queue.
C++ Programming: Program Design Including Data Structures, Fifth Edition 74
• The only way is to reset the linear queue, for a
fresh start.
• Circular Queue is also a linear data structure,
which follows the principle of FIFO(First In First
Out), but instead of ending the queue at the last
position, it again starts from the first position
after the last, hence making the queue behave
like a circular data structure.
75
Basic features of Circular Queue

• In case of a circular queue, head pointer will


always point to the front of the queue, and tail
pointer will always point to the end of the queue.

• Initially, the head and the tail pointers will be


pointing to the same location, this would mean
that the queue is empty.

C++ Programming: Program Design Including Data Structures, Fifth Edition 76


• New data is always added to the location
pointed by the tail pointer, and once the data is
added, tail pointer is incremented to point to the
next available location.

77
• In a circular queue, data is not actually removed
from the queue. Only the head pointer is
incremented by one position when dequeue is
executed. As the queue data is only the data
between head and tail, hence the data left
outside is not a part of the queue anymore,
hence removed.

C++ Programming: Program Design Including Data Structures, Fifth Edition 78


C++ Programming: Program Design Including Data Structures, Fifth Edition 79
• The head and the tail pointer will get reinitialized
to 0 every time they reach the end of the queue.

C++ Programming: Program Design Including Data Structures, Fifth Edition 80


• Also, the head and the tail pointers can cross
each other. In other words, head pointer can be
greater than the tail. Sounds odd?

This will happen when we dequeue the queue a


couple of times and the tail pointer gets re-
initialized upon reaching the end of the queue.

C++ Programming: Program Design Including Data Structures, Fifth Edition 81


C++ Programming: Program Design Including Data Structures, Fifth Edition 82
Going Round and Round
• Another very important point is keeping the value
of the tail and the head pointer within the
maximum queue size.

• In the diagrams above the queue has a size of 8,


hence, the value of tail and head pointers will
always be between 0 and 7.

83
• This can be controlled either by checking every
time whether tail or head have reached
the maxSize and then setting the value 0 or, we
have a better way, which is, for a value x if we
divide it by 8, the remainder will never be greater
than 8, it will always be between 0 and 0, which
is exactly what we want.
• So the formula to increment
the head and tail pointers to make them go
round and round over and again will be:
head = (head+1) % maxSize
tail = (tail+1) % maxSize 84
Implementation of Circular Queue
• Initialize the queue, with size of the queue
defined (maxSize), and head and tail pointers.

• enqueue: Check if the number of elements is


equal to maxSize - 1:
• If Yes, then return Queue is full.
• If No, then add the new data element to the
location of tail pointer and increment the tail
pointer.
85
• dequeue: Check if the number of elements in the
queue is zero:
If Yes, then return Queue is empty.
If No, then increment the head pointer.
• Finding the size:
If, tail >= head, size = (tail - head) + 1
But if, head > tail,
then size = maxSize - (head - tail) + 1

C++ Programming: Program Design Including Data Structures, Fifth Edition 86


#include<iostream>
using namespace std;
#define SIZE 10
class CircularQueue
{
int a[SIZE];
int rear; //same as tail
int front; //same as head
public:
CircularQueue()
{
rear = front = -1;
}
// function to check if queue is full
bool isFull()
{
if(front == 0 && rear == SIZE - 1)
{
return true;
}
if(front == rear + 1)
{
return true;
}
return false; 87
// function to check if queue is empty
bool isEmpty()
{
if(front == -1)
{
return true;
}
else
{
return false;
}
}
//declaring enqueue, dequeue, display and size functions
void enqueue(int x);
int dequeue();
void display();
int size();
};

C++ Programming: Program Design Including Data Structures, Fifth Edition 88


// function enqueue - to add data to queue
void CircularQueue :: enqueue(int x)
{
if(isFull())
{
cout << "Queue is full";
}
else
{
if(front == -1)
{
front = 0;
}
rear = (rear + 1) % SIZE; // going round and round
concept
// inserting the element
a[rear] = x;
cout << endl << "Inserted " << x << endl;
}
}

89
// function dequeue - to remove data from queue
int CircularQueue :: dequeue()
{
int y;

if(isEmpty())
{
cout << "Queue is empty" << endl;
}
else
{
y = a[front];
if(front == rear)
{
// only one element in queue, reset queue after
removal
front = -1;
rear = -1;
}
else
{
front = (front+1) % SIZE;
}
return(y); 90
}
void CircularQueue :: display()
{
/* Function to display status of Circular Queue */
int i;
if(isEmpty())
{
cout << endl << "Empty Queue" << endl;
}
else
{
cout << endl << "Front -> " << front;
cout << endl << "Elements -> ";
for(i = front; i != rear; i= (i+1) % SIZE)
{
cout << a[i] << "\t";
}
cout << a[i];
cout << endl << "Rear -> " << rear;
}
}

91
int CircularQueue :: size()
{
if(rear >= front)
{
return (rear - front) + 1;
}
else
{
return (SIZE - (front - rear) + 1);
}
}
// the main function
int main()
{
CircularQueue cq;
cq.enqueue(10);
cq.enqueue(100);
cq.enqueue(1000);
cout << endl << "Size of queue: " << cq.size();
cout << endl << "Removed element: " << cq.dequeue();
cq.display();
system("pause");
return 0;
} 92

You might also like