You are on page 1of 17

Linked List Implementation of Stack & Queue

Stack: Linked List Implementation


Push

and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top of the stack Nodes are removed from the front (top) of the list

List Stack Example


push(6);

top

List Stack Example


push(6); push(1);

top 1 6

List Stack Example


push(6); push(1); push(7);

top

7 1 6

List Stack Example


8
top 7 1 6
push(6); push(1); push(7); push(8);

List Stack Example


8
top 7 1 6
push(6); push(1); push(7); push(8); pop();

List Stack Example


push(6); push(1); push(7); push(8); pop();

top

7 1 6

Implementing queues using arrays

Simple implementation
The size of the queue must be determined when a stack object is declared Space is wasted if we use less elements We cannot "enqueue" more elements than the array can hold

Implementing queues using linked lists

Allocate memory for each new element dynamically Link the queue elements together
Use two pointers, qFront and qRear, to mark the front and rear of the queue

10

Enqueuing (non-empty queue)

11

Enqueuing (empty queue)

We need to make qFront point to the new node also


qFront = NULL New Node

qRear = NULL
newNode
12

Dequeueing (the queue contains more than one element)

13

Dequeueing (the queue contains only one element)

We need to reset qRear to NULL also


qFront After dequeue:

Node
qRear

qFront = NULL qRear = NULL

14

Declaration of a linked list in C


struct node { int val; struct node * link; } struct node *start = null; start = (struct node *)malloc(sizeof(struct node))

15

Inserting a new node at the beginning


struct node *new; new = (struct node *)malloc(sizeof(struct node)) if(start == null) { start = new; new->link=null; } else { new->link=start; start=new; }
16

Inserting a new node at a given position


struct node *new; new = (struct node *)malloc(sizeof(struct node)) if(loc == 1) { insert_beg(); } else { ptr = start; struct node *temp = (struct node *)malloc(sizeof(struct node)) for(i=1;i<2;i++) { temp = ptr; ptr=ptr->link; } } temp-link=new; new->link=ptr;
17

You might also like