by ashutosh kumar singhprofashutosh.com/wp-content/uploads/2019/03/ds7.pdf · a list is usually...
TRANSCRIPT
Data Structures and Algorithms
© Ashutosh Kumar Singh
By
Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Stacks
Queues
Linked List
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Definition
Linked list and Dynamic memory allocation
Operations of linked list
Strength and weaknesses
Data Structures and Algorithms
© Ashutosh Kumar Singh
A list is usually referred as a sequence of similar elements.
Examples of lists are a list of employee names, television program schedules, menu, etc.
All elements in a list must have an element before and after them, with the exception of the first and last elements.
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms ©
Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh 11
A node’s successor is the next node in the sequence
The last node has no successor
A node’s predecessor is the previous node in the sequence
The first node has no predecessor
A list’s length is the number of elements in it
A list may be empty (contain no elements)
Data Structures and Algorithms
© Ashutosh Kumar Singh
typedef struct nodetype{
int info;
struct nodeType *next;
} node;
node *head;
Data Structures and Algorithms
© Ashutosh Kumar Singh
Singly Linked Lists
Doubly Linked List
Circular Linked List
Data Structures and Algorithms
© Ashutosh Kumar Singh
This list consists of a number of nodes
Each node contains at least A piece of data (any type)
Pointer to the next node in the list
Head: pointer to the first node
The last node points to NULL
A
Head
B C
A
data pointer
node
Data Structures and Algorithms
© Ashutosh Kumar Singh
Also known as two-way linked list Each node points to not only successor but the
predecessor There are two NULL: at the first and last nodes in the list Advantage:
given a node, it is easy to visit its predecessor. Convenient to traverse lists backwards
Disadvantage: Each node requires an extra pointer, more space Insertion or deletion takes a bit longer
A
Head
B C
Data Structures and Algorithms
© Ashutosh Kumar Singh
Advantages: Can be traversed in either
direction (may be essential for some programs)
Some operations, such as deletion and inserting before a node, become easier
Disadvantages: Requires more space
List manipulations are slower (because more links must be changed)
Greater chance of having bugs (because more links must be manipulated)
Data Structures and Algorithms
© Ashutosh Kumar Singh
The last node points to the first node of the list
How do we know when we have finished traversing the list? (Tip: check if the pointer of the current node is equal to the head.)
A
Head
B C
Data Structures and Algorithms
© Ashutosh Kumar Singh
Circular linked lists do not have ends
There is no node with NULL pointer
Application: Round Robin Algorithm for utilizing the
computer resources
Have to assure that no process accesses the resource before all the process finished.
Data Structures and Algorithms
© Ashutosh Kumar Singh
Its memory space can expand or contract as the program executes.
Allows it to obtain and release memory when there is a need.
Data Structures and Algorithms
© Ashutosh Kumar Singh
Dynamic memory allocation Obtain and release memory during execution
malloc
Takes number of bytes to allocate Use sizeof to determine the size of an object
Returns pointer of type void * A void * pointer may be assigned to any pointer If no memory available, returns NULL
ExamplenewPtr = malloc( sizeof( struct node ) );
free
Deallocates memory allocated by malloc Takes a pointer as an argument free ( newPtr );
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Traversing the linked list
Inserting an item in the list
Deleting an item from the list
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Data Structures and Algorithms
© Ashutosh Kumar Singh
Traversing means moving along a list.
We traverse a list to find matching elements or to print out the elements.
To traverse, we use pointers to move from one node to another until the last node in the list.
Data Structures and Algorithms
© Ashutosh Kumar Singh
Follow the pointers
Display the contents of the nodes as they are traversed
Stop when the next pointer points to NULL
B C DA
Head
Data Structures and Algorithms
© Ashutosh Kumar Singh
void traverse (node *head) {
while (head!=NULL)
{
printf(“%d/n”, head info);
head = head next ;
}
}
Algorithm 1. Set PTR:=START2. Repeat Step 3 and 4 while PTR= NULL.3. Apply PROCESS to INFO[PTR].4. Set PTR:=LINK[PTR].[END of step 2 loop.]5. Exit
Data Structures and Algorithms
© Ashutosh Kumar Singh
Inserting a new node before the head.
A new node is inserted before the current head node
Only next pointer needs to be modified
Requires two steps:
Update the next pointer of new node, to point the current head
Update head pointer to point to the new
A B CN
New Node Head
A B CN
Head
Data Structures and Algorithms
© Ashutosh Kumar Singh
Inserting a new node after the tail
Need to modify two next pointers
Position node and new node
Requires two steps:
New nodes points to the next node of the position
Last node next pointer points to the new node
A B C N
Head
A C NA
Head
Data Structures and Algorithms
© Ashutosh Kumar Singh
Inserting a new node at the Middle
Need to modify two next pointers
Last nodes next pointer and new nodes nest pointer
Requires two steps:
New nodes next pointer points to NULL
A B C
N
Head
New Node
Position Node
Data Structures and Algorithms
© Ashutosh Kumar Singh
Writ e the code for Inserting a new node to linked list
Data Structures and Algorithms
© Ashutosh Kumar Singh
Deleting the first Node
Deleting the last node
Deleting an intermediate node
Data Structures and Algorithms
© Ashutosh Kumar Singh
Algorithm Identify the location of the node to be deleted
Identify the pointers involved in the process
The node is removed from the list by linking the nodes before and after it
The node that is removed from the linked list is deleted from the memory using free(tempPtr)
Data Structures and Algorithms
© Ashutosh Kumar Singh 34
Since all the action happens at the top of a stack, a singly-linked list (SLL) is a fine way to implement it
The header of the list points to the top of the stack
44 97 23 17
myStack:
Pushing is inserting an element at the front of the list
Popping is removing an element from the front of the list
Data Structures and Algorithms
© Ashutosh Kumar Singh
10 x
3000
20 3000
6000
3000
TOPTOP
6000
10 6000
8000
TOP
8000
STACK GROWTH
Data Structures and Algorithms
© Ashutosh Kumar Singh
typedef struct nodetype{
int info;
struct nodeType *next;
} stack;
node *top;
Data Structures and Algorithms
© Ashutosh Kumar Singh
int IsEmpty(Stack S);
Stack CreatStack(void);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
void Pop(Stack S);
ElementType Top(Stack S);
Data Structures and Algorithms
© Ashutosh Kumar Singh
Test for an empty stack
int Isempty(Stack S)
{
return (SNext == NULL)
}
Data Structures and Algorithms
© Ashutosh Kumar Singh
Create an empty stackstack CreatStack(void)
{ Stack S;
S=malloc(sizeof(structNode));
if (S==NULL)
FatalError(“Out of space!!!”);
MakeEmpty(S)
return(S);
}
void MakeEmpty(Stack S)
{ if (S==NULL)
printf(“Error message!”);
else
while (!IsEmpty(S))
pop(S)
}
Data Structures and Algorithms
© Ashutosh Kumar Singh
Push onto a stackvoid Push(ElementType X, Stack S)
{ PtrtoNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if (TmpCell == NULL)
fatalError(“message”);
else
{ TmpCell Element = X;
TmpCell Next = S Next;
S Next = TmpCell;
}
}
Data Structures and Algorithms
© Ashutosh Kumar Singh
Return top element in a stack
ElementType Top(Stack S)
{ if (!IsEmpty(S))
return (S Next Element);
Error(“Empty stack”);
return 0;
}
Data Structures and Algorithms
© Ashutosh Kumar Singh
Pop from a stackvoid Pop(Stack S)
{ PtrToNode FirstCell;
if (ISEmpty(S);
Error (“Empty stack”);
else
{ FirstCell = S Next;
S Next =S Next Next;
free(FirstCell);}
}
Data Structures and Algorithms
© Ashutosh Kumar Singh
Algo push
If AVAIL = NULL, then write overflow and exit
NEW:= AVAIL
AVAIL:=LINK[AVAIL]
INFO[NEW]:=ITEM
LINK[NEW]:=TOP
TOP:=NEW
EXIT
…
data link
NULL
top
Growth
of stack
Data Structures and Algorithms
© Ashutosh Kumar Singh
ALGO
If TOP=NULL , write underflow and exit.
NEW:=TOP
TOP:=LINK[TOP]
LINK[NEW]:=AVAIL
AVAIL:=NEW
EXIT
Data Structures and Algorithms
© Ashutosh Kumar Singh 45
With a linked-list representation, overflow will not happen (unless you exhaust memory, which is another kind of problem)
Underflow can happen, and should be handled the same way as for an array implementation
When a node is popped from a list, and the node references an object, the reference (the pointer in the node) does not need to be set to null Unlike an array implementation, it really is removed-
-you can no longer get to it from the linked list
Hence, garbage collection can occur as appropriate
Data Structures and Algorithms
© Ashutosh Kumar Singh
Strength Easily to insert/ delete node. Dynamic memory allocation.
Weaknesses Not indexed - we need to traverse a list of
elements to find a certain data. (an inefficient and a time-consuming process).
Using pointers - a failure to set pointer to NULL when it does not point to any object, may result in an unpredictable result or system crash.
Data Structures and Algorithms
© Ashutosh Kumar Singh 47
In a queue, insertions occur at one end, deletions at the other end
Operations at the front of a singly-linked list (SLL) are O(1), but at the other end they are O(n) Because you have to find the last element each time
BUT: there is a simple way to use a singly-linked list to implement both insertions and deletions in O(1) time You always need a pointer to the first thing in the list You can keep an additional pointer to the last thing in
the list
Data Structures and Algorithms
© Ashutosh Kumar Singh 48
In an SLL you can easily find the successor of a node, but not its predecessor Remember, pointers (references) are one-way
If you know where the last node in a list is, it’s hard to remove that node, but it’s easy to add a node after it
Hence, Use the first element in an SLL as the front of the
queue Use the last element in an SLL as the rear of the queue Keep pointers to both the front and the rear of the SLL
Data Structures and Algorithms ©
Ashutosh Kumar Singh 49
17
Node to be
enqueued
To enqueue (add) a node:
Find the current last node
Change it to point to the new last node
Change the last pointer in the list header
2344
lastfirst
97
Data Structures and Algorithms
© Ashutosh Kumar Singh 50
Before we insert new element in a queue
It is necessary to test whether queue still have some space to accommodate the incoming element i.e. the queue is full or not
If it is full then enqueue operation can be performed
boolean isFull (queue *pq)
{
if ((pq front ==0) && (pq rear == CAPACITY-1 )) return true;
else
return false;
}
Data Structures and Algorithms
© Ashutosh Kumar Singh 51
To dequeue (remove) a node: Copy the pointer from the first node into the header
44 97 23 17
lastfirst
Data Structures and Algorithms
© Ashutosh Kumar Singh 52
Before we remove an element from a queue
It is necessary to test whether queue still have some element i.e. to test the queue is empty or not
If it is not empty then dequeue operation can be performed
boolean isEmpty (queue *pq)
{
if (pq front ==-1)
return true;
else
return false;
}
Data Structures and Algorithms
© Ashutosh Kumar Singh 53
With an array implementation: you can have both overflow and underflow
you should set deleted elements to null
With a linked-list implementation: you can have underflow
overflow is a global out-of-memory condition
there is no reason to set deleted elements to null
Data Structures and Algorithms
© Ashutosh Kumar Singh 54
Write algorithm for enqueue operation on linear Queue
Data Structures and Algorithms
© Ashutosh Kumar Singh
55
Stacks Insert at the top of the stack (push)Delete at the top of the stack (pop)
Queues Insert at the rear of the queue (append)Delete at the front of the queue (serve)
Lists Insert at any position in the list.Delete at any position in the list.
Data Structures and Algorithms
© Ashutosh Kumar Singh
Linked List
Type of Linked List
Linked List and Dynamic Memory
Basic Operation on Linked List
Implementation of Stack
Implementation of Linked List
Data Structures and Algorithms
© Ashutosh Kumar Singh
1. Sahni S., Data Structures, Algorithms and Applications in C++, Mc
Graw Singapore, 1998.
2. Cormen T. H., Leiserson C. E. and Rivest R. L., Introduction to
Algorithms, Prentice Hall India, New Delhi, 1990.
3. Nyhoff, L., ADTs, Data Structures, and Problem Solving with C++,
Pearson Prentice Hall, 2005.
4. Weiss, M., Data Structures and Algorithm Analysis in C++, Addison
Wesley, 2006.
5. Main, M. and Savitch, W., Data Structures & Other Objects Using C++,
Addison Wesley, 2005.
6. Carrano, F., Data Abstraction and Problem Solving with C++: Walls and
Mirrors, Addison Wesley, 2005.
7. www.users.drew.edu/sbradsha/CSCI1
8. www.cs.nyu.edu/courses