o A linkedlist is a linear data structure, in which the
elements are not stored at contiguous memory
locations.
o The elements in a linked list are linked using pointers
o It is self-referential structure.
o It is a collection of elements called nodes,
A node stores two types of fields:
o Data items and a pointer/link .
2
Daata Structure & Algorithm
Introduction
3.
o The datafield holds the actual elements on the list
o The pointer field contains the address of the next
node in the list- Singly linked list
o The pointer field contains the address of the
previous node in the list - doubly linked list
Cont
’
3
Daata Structure & Algorithm
4.
o Let’s Store12, 34, 40 and 56 using linked list
o First Create four different nodes then create link
How to access the first element?
Cont
’
100 300 400
12 300 34 400 40 500 56 NULL
500
100 head
4
Daata Structure & Algorithm
5.
o In linkedlist, flexible space use by dynamically
allocating space for each element as needed.
o Successive elements are connected by
pointers and last element points to NULL.
o This implies that one need not know the size of the
list in advance.
Can change memory during execution.
So, memory is efficiently utilized compared to array.
5
Daata Structure & Algorithm
Cont
’
6.
• The figurebelow shows a linked list called scores
that contains four elements.
• And also shows an example of an empty linked
list.
6
Daata Structure &
Algorithm
7.
Array Vs Linked
List
Both an array and a linked list are representations of a list of
items in memory. The only difference is the way in which the
items are linked together.
Array:
Sequential mapping
Elements are fixed distance apart.
Makes insertion or deletion at any arbitrary position in an
array a costly operation.
Randomly accessing any element…. Etc.
7
Daata Structure & Algorithm
8.
Linked List:
Not necessarythat the elements be at a fixed
distance apart
An element is required to be linked with a previous
element of the list
Suitable for Inserting/deleting an element.
Done by storing the address of the next element
8
Daata Structure & Algorithm
Cont
’
Cont
’
Like arraya linked list must have a name.
The name of a linked list is the name of the head pointer
that points to the first node of the list.
10
Daata Structure & Algorithm
11.
Linked list operations
Thefollowing are the basic operations supported by a
list.
⚫Display − Displays the complete list.
⚫Search − Searches an element using the given key.
⚫Insertion − Adds an element at the beginning of
the list.
⚫Deletion − Deletes an element at the beginning of
the list. Deletes an element using the given key.
Daata Structure & Algorithm 11
12.
Revision on Pointers
Datastructures&Algorithms
12
⚫A pointer is a variable that points to another
variable.
⚫This means that a pointer holds the memory address
of another variable.
⚫ The pointer does not hold a value in the
traditional sense; instead, it holds the address of
another variable.
⚫A pointer "points to" that other variable by holding a
copy of its address.
Daata Structure & Algorithm 12
13.
Display the contentof list
Steps:
⚫ Set a temporary pointer to point to the same thing as the start
pointer.
⚫ If the pointer points to NULL, display the message "End of list" and
stop.
⚫ Otherwise, display the data values of the node pointed to by the start
pointer.
⚫ Make the temporary pointer point to the same thing as the next
pointer of the node it is currently indicating.
⚫ Jump back to step 2.
Daata Structure & Algorithm 13
14.
Searching operation onLinked List
14
Daata Structure & Algorithm
Since nodes in a linked list have no names, we use
two pointers, pre (for previous) and cur (for
current).
At the beginning of the search, the pre pointer is
null and the cur pointer points to the first node.
The search algorithm moves the two pointers
together towards the end of the list.
Inserting
• Before insertioninto a linked list, we first apply the
searching algorithm.
• If the flag returned from the searching algorithm is false, we
will allow insertion, otherwise we abort the
insertion algorithm, because we do not allow data
with duplicate
values.
• You can insert in to a linked list at the beginning, the end,
and the middle of the list.
16
Daata Structure & Algorithm
17.
Insert at thefront (beginning)
Data structures&Algorithms
17
Steps:
⚫Allocate a new node.
⚫Insert new element values.
⚫Make the next pointer of the new node point to old
head (start).
⚫Update head (start) to point to the new node.
Daata Structure & Algorithm 17
18.
Inserting a nodeat the beginning of a linked list
Cont’
Data structures&Algorithms 18
Daata Structure & Algorithm 18
19.
Inserting at theEnd
Steps
⚫Allocate a new node.
⚫Set the node data values and make the next pointer
of the new node point to NULL.
⚫Make old last node’s next pointer point to the new
node.
⚫Update end to point to the new node.
Data structures&Algorithms
19
Daata Structure & Algorithm 19
20.
Inserting a nodeat the end of the linked list
20
Daata Structure &
Algorithm
21.
Deleting
21
Daata Structure &Algorithm
Before deleting, we apply the search algorithm.
If the flag returned from the search algorithm is
true (the node is found), we can delete the node
from the linked list. However, deletion is simpler than
insertion.
We have only two cases: deleting the first node and
deleting any other node.
Deletion of the last and the middle nodes can be done
22.
Deleting the firstnode of a linked list
Cont’
22
Daata Structure & Algorithm
23.
Implementation of LLusing C++
Daata Structure & Algorithm
Creating a node
struct node{
int data;
node *next;
};
Note:
Self
referential
structure
means…..
23
23
24.
Cont…
Daata Structure &Algorithm
24
Adding a node to the front (of a singly linked list)
void insert_front(int x) {
node *temp=new node;
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else
{
temp->next = head;
head = temp;
}}
24
25.
Cont…
Daata Structure &Algorithm
Adding a node to the end (of a singly linked list)
void insert_end(int x) {
node *temp=new node;
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else
node *temp2 = head;
while(temp2->next!=NULL) {
temp2 = temp2->next; }
temp2->next = temp; }
25
25
26.
Cont…
Daata Structure &Algorithm
Deleting a node from the front( of a singly linked list)
void delete_front() {
node *temp;
if(head==NULL)
cout <<"No data insiden";
else
temp = head;
head = head->next;
delete temp; }
26
26
27.
• The Nodesshown on the previous slides were
singly linked list.
• A node refers only to the next node in the structure
• It is also possible to have doubly linked nodes.
• The node has a reference to the next node in the
structure and the previous node in the structure as
well.
27
Daata Structure & Algorithm
Doubly linked list
28.
Pointers existbetween adjacent nodes in both
directions. The list can be traversed either forward
or backward. Usually two pointers are maintained
to keep track of the list, head and tail.
Cont’
28
Daata Structure & Algorithm
29.
Circular Linked List
⚫Circular Linked List is little more complicated linked data
structure.
⚫ In the circular linked list the previous element stores the
address of the next element and the last element stores the
address of the starting element.
⚫ The elements points to each other in a circular way which
forms a circular chain.
Daata Structure & Algorithm 29
30.
Applications of linkedlists
A linked list is a very efficient data structure for
sorted list that will go through many operations.
A linked list is a dynamic data structure in which
the list can start with no nodes and then grow as
new nodes are needed.
A node can be easily deleted without moving
other nodes, as would be the case with an array.
30
Daata Structure & Algorithm
31.
For example,a linked list could be used to hold the
records of students in a school. Each quarter or
semester, new students enroll in the school and
some students leave or graduate.
Note: A linked list is a suitable structure if a large number
of insertions and deletions are needed, but searching a
linked list is slower than searching an array.
31
Daata Structure & Algorithm
Cont’
32.
Advantages of LinkedLists
⚫They are a dynamic in nature which allocates the
memory when required.
⚫Insertion and deletion operations can be easily
implemented.
⚫Stacks and queues can be easily executed.
⚫Linked List reduces the access time.
Daata Structure & Algorithm
Cont’
32
32
33.
Disadvantages of LinkedLists
⚫the memory is wasted as pointers require extra
memory for storage.
⚫No element can be accessed randomly; it has to
access each node sequentially.
⚫Reverse Traversing is difficult in linked list.
Daata Structure & Algorithm
Cont’
33
33
34.
34
Daata Structure &Algorithm
Reading Assignment
⚫Read about the implementation of doubly and
circular LL
34
Introduction
Daata Structure &
Algorithm
2
Stack is an ordered group of homogeneous items of elements.
Is a simple data structure, in which insertion and deletion
occur at the one end (at the top).
Anything added to the stack goes on the “top” of the stack
Anything deleted from the stack is taken from the “top” of the
stack in the reverse order from that in which they were
inserted.
36
37.
Cont’
3
Inserting an itemreferred to as pushing to the stack.
Deleting an item referred to aspopping it
from the stack.
So,A stack is a last-in-first-out (LIFO) data
structure.
Last in-delete first
First in-delete last
Daata Structure &
Algorithm
37
8
Cont’
In general, thefollowing are basic activities on a stack:
push an item onto the stack
The two basic operations
pop an item from the stack
retrieve the top element of the stack,
initialize the stack,
check whether the stack is empty, and
check whether the stack is full.
Daata Structure &
Algorithm
42
43.
Implementation of Stack
9
To implement stack we use an array.
Since the insertion and deletion operations on a stack are made only
at the end of the stack, using an array is efficient.
Basic stack methods
isEmpty()
push(item)
pop()
peek()
Daata Structure &
Algorithm
43
44.
IDEA:
Push() {
if thereis room {
put an item on the top of the
stack
…..}
else {
give an error
message “Stack
overflow”
} Daata Structure &
Algorithm
Push operation
10
44
45.
Array Implementation ofStacks: Push
operation
Daata Structure &
Algorithm
Step-1: Increment the stack top by 1.
Check whether it is always less than the Upper Limit of the stack.
If it is less than the Upper Limit go to step-2
else
report -"Stack Overflow"
Step-2: Put the new element at the position pointed by the Top
/Stack Overflow means when the stack become
full.
11
45
46.
Algorithm
Daata Structure &
Algorithm
intstack[upper_limit];
int top= -1; /*stack is empty*/
….
main()
{… push(item);
…..}
push(int item){
top = top + 1;
if(top < upper_limit)
stack[top] = item; /*step-1 &
2*/ else
cout<<"Stack
Overflow"; }
12
46
47.
IDEA:
Pop(){
if stack notempty {
remove the top item from the
stack
}
else{
give an error message
}
}
Daata Structure &
Algorithm
13
POP operation
47
48.
Step-1: If theStack is empty then give the alert
"Stack underflow" and
quit; else go to step-2
Step-2: a) Hold the value for the element pointed by the
top
b)Put a NULL value instead
c)Decrement the TOP by 1
Daata Structure &
Algorithm
14
Array Implementation of Stacks: POP operation
48
49.
int pop(){
if(top==-1){
Daata Structure&
Algorithm
cout<<"Stack Underflown";
return -1;
}else
{int
t=stack[top]; top
--;
return t;} }
NB: /tack underflow means when the stack become
empty.
Algorith
m 15
49
50.
16
To reversea word. You push a given word to stack - letter by
letter - and then pop letters from the stack.
An "undo" mechanism in text editors; this operation is
accomplished by keeping all text changes in a stack.
Undo/Redo stacks in Excel or Word.
Language processing : space for parameters and local variables is
created internally using a stack. compiler's syntax check for matching
braces is implemented by using stack.
A garage that is only one car wide. To remove the first car in we
have to take out all the other cars in after it.
Back/Forward stacks on browsers.
Daata Structure &
Algorithm
Application of Stack: Real time
50
51.
17
Stack can beused to:
Infix to Postfix Transformation
Memory management
During the execution of recursive programs
Implementing function or method calls
Convert Decimal to Binary
……………and so on.
Daata Structure &
Algorithm
Application of Stack more…
51
52.
Infix to Postfix
Conversion
DaataStructure &
Algorithm
18
Revision on expression
⚫Expressions have operators (+, -, *, /, etc) and
operands (numbers, variables)
⚫In everyday use, we write the operators
in between the operands like
“4 + 5” means “add 4 and 5”…. called infix notation
⚫No reason why we couldn’t write the two operands
first,
then the operator like
“4 5 +” would mean “add 4 and 5”…called postfix 52
53.
Why Post fix?
Doesnot require parentheses
Some calculators make you type in that way
Easy to process by a program
• Example
1 2 + 7 * 2 %...........has no parentheses
(3 + (5 / 3) * 6) – 4 ……..has
parentheses
Daata Structure &
Algorithm
Cont’
19
53
54.
⚫It is commonto use infix notation for our day to day work.
But in computer
system, postfix notation is widely used.
⚫As computer scientist, postfix notation has important in stack.
So, arithmetic expressions can be convert into form of
postfix notation
4 + 5 is infix notation
4 5 + is postfix notation
Daata Structure &
Algorithm
20
Cont’
54
55.
⚫Rules:
Operands immediatelygo directly to output/postfix.
Operators are pushed into the stack (including parenthesis)
Check to see if stack top operator is less than current operator
If the top operator is less than, push the current operator onto
stack.
If the top operator is greater than or equal the current, pop top
operator and push to postfix expression , push current
operator onto stack
Daata Structure &
Algorithm
21
Cont’
55
56.
Priority : */..Same
Priority : + -..Same
Priority : (
If we encounter a right parenthesis, pop from
stack until we get matching left parenthesis.
Do not write parenthesis in postfix
expression.
Daata Structure &
Algorithm
22
Cont’
56
57.
Check: 3 +2 * 4=?
23
ab c * +
a +b
ab +
a + b *c
ab + c *
Daata Structure &
Algorithm
a * b +c
ab * c +
(a + b )
*c
Eg1:Infix ExpressionEquivalent Postfix
Expression
57
58.
24
((A + B)* C) / (D - E)
C
A B
D E
*
+
/
-
C
A B
D E
*
+
/
-
A B + C * D E-/
Daata Structure &
Algorithm
Eg-2: Convert this into postfix
expression
58
59.
25
Eg-3: 6 3+ 2 * = ?
Step 1:Push 6 into
stack Step 2:push 3
into stack Step 3:apply
+(3+6=9)
Step 4:push the result into
stack Step 5:push 2 into stack
Step 6:apply *(2 * 9=18)
So, the result is 18(6 3 + 2 * =
18)
6
3
6
2
9
18
9
How to Evaluate postfix expressions using
stack?
Daata Structure &
Algorithm
59
60.
Infix
Daata Structure &
Algorithm
a)A + B * C - D / E
b) + B * C - D / E A
c) B * C - D / E + A
d) * C - D / E + A B
e) C - D / E + * A B
f) - D / E + * A B C
g) - D / E + A B C *
h) - D / E A B C *+
i) D / E - A B C *+
j) / E - A B C *+D
K) E - / A B C *+D
l) A B C *+D E
A B C *+D E-/
Infix to Postfix Eg-
4 26
A + B * C - D / E
Stack(bot->top)
Postfix
60
61.
Memory management
Daata Structure&
Algorithm
27
⚫ The assignment of memory takes place in contiguous memory blocks.
⚫ We call this stack memory allocation because the assignment takes place
in the function call stack.
⚫ The size of the memory to be allocated is known to the compiler.
⚫ When a function is called, its variables get memory allocated on the stack.
⚫ When the function call is completed, the memory for the variables is
released.
⚫ All this happens with the help of some predefined routines in the compiler.
61
Definition
• Like astack, special kind of linear data structure
• Stores a set of elements in a particular order
• Unlike stack, queue use the FIRST IN FIRST
OUT( FIFO) principle
It means that the first element inserted is the first one to
be removed
One of the queue end is called front and the other end is
called rear.
Types of Queue
• Simple Queue
• Circular Queue
• Priority 2
Daata Structure & Algorithm 63
64.
Simple Queue
• Itis the most basic queue in which the insertion of an item is
done at the front of the queue and deletion takes place at the
end of the queue.
Additions (insertions or enqueue) are done at the rear only
Removals (deletions or dequeue) are made from the front
only.
3
Daata Structure & Algorithm 64
65.
Example 1: Busstation
Remove a person from the
queue
Bus
Stop
front
rear
rear rear rear rear
Daata Structure & Algorithm 65
70
Other examples
Softwarequeues are similar to physical ones: like queuing
at
The supermarket
Airport Security Check
The bank,
Cinemas, etc.
Daata Structure & Algorithm
71.
Features
A list structurewith two access points called the front
and
rear.
All insertions (enqueue) occur at the rear and
deletions (dequeue) occur at the front.
Varying length (dynamic).
Homogeneous
components
71
Daata Structure & Algorithm
Operations…
4 1 3
14 1 3
5 1 4 1 3
5 1 4
5 1 4 1
5 1
enqueue(1);
enqueue(5);
dequeue();
dequeue();
dequeue();
Rear Front
Given the following Queue, how
will it change when we apply the
given operations?
73
Daata Structure & Algorithm
74.
Circular
Queue
• A circularqueue is a special case of a simple queue in which
the
last member is linked to the first.
• The last node is connected to the first node.
• That is why it is called circular
• The first location is viewed after the last one.
• Overflow occurs when all the locations are filled.
74
Daata Structure & Algorithm
75.
75
Operations
• enQueue(insertion): usedto insert an element into the
circular queue. In a circular queue, the new element is
always inserted at Rear position.
Check whether queue is Full :
Check ((rear == SIZE-1 && front == 0) | | (rear == front-1))
– If it is full then display Queue is full.
– If queue is not full then, check:
if (rear == SIZE – 1 && front != 0)
if it is true then set rear=0 and insert element.
Daata Structure & Algorithm
76.
76
Cont
…
• deQueue(deletion) usedto delete an element
from the circular queue.
• In a circular queue, the element is always deleted
from front position.
1. Check whether queue is Empty means check (front==-1).
2.If it is empty then display Queue is empty. If queue is not
empty then step 3
3. Check if (front==rear) if it is true then set front=rear= -1
else check if (front==size-1), if it is true then set front=0
and return the element.
Daata Structure & Algorithm
77.
77
Priority
Queue
A priorityis the extension queue. It is a collection of
elements such that each element has been assigned a priority
and
the items are removed from the queue according to the
priority.
An element of higher priority is processed before any
element of lower priority.
Two elements with the same priority are processed
according to the order in which they were added to the
Daata Structure & Algorithm
78.
Cont
’
Ascending Priority Queue:Collection of items into which item
can be inserted arbitrarily & the smallest item can be removed.
Descending Priority Queue: Collection of items into which item
can be inserted arbitrarily & the largest item can be removed.
78
Daata Structure & Algorithm
79.
79
Queue
Applications
• A queuedata structure is generally used in scenarios where
the FIFO approach has to be implemented.
In operating systems to manage resources
Handling hardware or real-time systems interrupts
Handling website traffic
Maintaining the playlist in media players
Daata Structure & Algorithm
80.
80
Cont
’
Shared resourcesmanagement (system
programming)
Access to the processor;
Access to the peripherals such as disks and
printers.
Application programs:
Simulations;
Packet Forwarding in Routers
Message queue in Windows
Daata Structure & Algorithm
81.
81
Cont
…
Event-driven simulation.[ customers in a line, colliding
particles ]
Numerical computation. [ reducing roundoff error ]
Data compression. [ Huffman codes ]
Graph searching. [ Dijkstra's algorithm, Prim's algorithm ]
Number theory. [ sum of powers ]
Artificial intelligence. [ A* search ]
Daata Structure & Algorithm
82.
82
Cont…
Statistics. [online median in data stream ]
Computer networks. [ web cache ]
Discrete optimization. [ bin packing, scheduling
]
Spam filtering. [ Bayesian spam filter ]
Daata Structure & Algorithm
83.
83
Array implementation ofqueue
• During implementation the following points are
undertaking.
Enqueue: add a new item at the rear
Dequeue: remove a item from the front
isEmpty: check whether the queue is empty or not
isFull: Check whether the queue is full or not
Size: return the number of items in the queue
Peek: return the front item
Daata Structure & Algorithm