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

4 Linked List

This document discusses linked lists, stacks, and queues. It defines linked lists as a sequence of nodes where each node contains a data field and a link to the next node. Single linked lists contain nodes with a single link field, while double linked lists contain nodes with both next and previous link fields. Common operations on linked lists include inserting and deleting nodes from the head, tail, or middle of the list. Stacks and queues are also discussed, along with their array and linked list implementations.

Uploaded by

AKASH PAL
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)
105 views

4 Linked List

This document discusses linked lists, stacks, and queues. It defines linked lists as a sequence of nodes where each node contains a data field and a link to the next node. Single linked lists contain nodes with a single link field, while double linked lists contain nodes with both next and previous link fields. Common operations on linked lists include inserting and deleting nodes from the head, tail, or middle of the list. Stacks and queues are also discussed, along with their array and linked list implementations.

Uploaded by

AKASH PAL
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/ 13

Chapter 4

Linked Lists, Stacks and Queues

LEARNING OBJECTIVES

 Data structure  Queue


 Linked list  Double-ended queue
 Single-linked list  Circular queue
 Double-linked list  Priority queue
 Circular linked list  Array implementation
 Double circular-linked list  Linked list implementation
 Stack  Linked list implementation of priority queue

Data strUctUre sinGLe-LinkeD List


Data structure represents the logical arrangement of data in com- List in which each node contains only one link field.
puter memory for easily accessing and maintenance.
Node structure
LinkeD List struct
A linked list is a data structure that consists of a sequence of nodes, {
each of which contains data field and a reference (i.e., link) to next int ele;
node in sequence. struct node ∗ next;
};
• Generally node of linked list is represented as self-referential typedef struct node Node;
structure.
• The linked list elements are accessed with special pointer(s) Creating a linked list with two
called head and tail.
nodes of type list node
Head Creating a linked list with 2 nodes
A B C Tail
struct node
Data Link
{
Int ele;
• The principal benefit of a linked list over a conventional array struct node ∗ next ;
is that the list elements can easily be added or removed without };
reallocation or reorganization of the entire structure because the typedef struct node Node ;
data items need not be stored contiguously in memory or on disk. Node ∗ ptr1, ∗ ptr2;
• Linked lists allow insertion and removal of nodes at any point ptr1 = getnode ();
in the list. ptr2 = getnode ();
• Finding a node that contains a given data, or locating the place if((ptr1) && (ptr2))
where a new node should be inserted may require scanning most {
or all of the list elements. Printf(“No memory”);
• The list element does not have to occupy contiguous memory. exit(1);
• Adding, insertion or deletion of list elements can be accom- }
plished with the minimal disruption of neighbouring nodes. Ptr1 → ele = 10;
3.48 | Unit 3  •  Programming and Data Structures

Ptr1 → next = ptr2; •• Step 4 allocates memory


Ptr2 → ele = 20; •• Step 5 read data
Ptr2 → next = NULL; •• Steps from 6 to 9 adjust reference
Head = ptr1; •• ‘if’ condition represents first insertion
the linked list appears as below
Insert in middle/random position of list
10 20 \ 1. void ins _ mid (int n, int pos)
2. {
Head int i = 1;
3. Node ∗ temp, N, P; //N,P represent
Operations on SLL (single-linked list) previous //& next nodes
­
•• Insert at Head 4. if (Head = = NULL)
•• Insert at Tail 5. {
•• Insert in Middle 6. ins _ head(n);
•• Delete Head 7. return;
•• Delete Tail 8. }
•• Delete Middle 9. temp = (Node ∗) malloc(sizeof(Node));
•• Search 10. temp → ele = n;
•• Display 11. P = head;
Declare two special pointers called head and tail as follows: 12. while (i < pos -1)
Node ∗Head, ∗Tail; 13. {
Head = Tail = NULL; P = P → next;
Head or tail is NULL represents list is empty. i++;
Steps for Insertion: }
14. N = P → next;
1. Allocate memory 15. temp → next = N;
2. Read data 16. P → next = temp;
3. Adjust references 17. }
•• step 4 checks, whether the insertion is into an empty
Insert head element
list.
1. void ins _ Head (int x)
•• If list is empty, invokes ins–head( ) function.
2. {
•• If list is not empty, then step 9 allocates memory.
3. Node ∗temp;
•• Step 10 reads data.
4. temp = (Node ∗) malloc(sizeof (Node));
•• Steps from 11 to 14 make the reference to the previ-
5. temp → ele = x;
ous and next nodes of new node to be inserted.
6. temp → next = Head;
•• Steps 15 and 16 create the reference to new node
7. Head = temp;
from previous node and from new node to next node.
8. if (Tail = = NULL)
9. Tail = Head; Example 1:  Head = Tail = NULL
10 } n = 5, P = NULL;
•• Step 4 allocates memory Here the list is empty. So,
•• Step 5 read data
Head
•• Steps from 6 to 9 adjust reference 5
Tail
•• ‘if ’ condition represents first insertion

Insert tail element Example 2:


1. void ins_tail (int x)
2. { Head 5 10 15 Tail
3. Node ∗temp;
4. temp = (Node ∗) malloc (sizeof (Node)); Insert element (n) 20 at position(pos) 3.
5. temp → ele = x; In current list, element 5 is the first element, 10 is the sec-
6. temp → next = NULL; ond and 15 is the third element.
7. Tail = temp; To insert an element at pos = 3, the new node has to be
8. if (Head = = NULL) placed between elements 10 and 15.
9. Head = Tail; Condition in step 4 is false so step 9 executes and allocates
10. } memory.
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.49

temp 5. {
6. printf("List empty");
7. return;
On completion of step 10 – 8. }
temp 9. x = Head → ele;
10. temp = Head;
20 11. if (Head = = Tail)
12. Head = Tail = NULL;
Step 11
13. else
Head
10 15 Tail
14. Head = Head → next;
5
15. printf ("Deleted element "%d", x);
p
16. free(temp);
Step 12, 13 17. }
While (i < pos – 1) Step 4 – Checks for list empty
{ Step 9 – Reads element to delete
P = P → next; Step 10 – Head referred by temp pointer
i++; Step 11 – Checks for last deletion
} Step 14 – Moves the head pointer to next
i < pos element in the list
1 < 2 Step 15 – Displays element to delete
Condition true, so Step 16 – Deallocates memory
Head
5 10 15 Delete tail element
p 1. void del _ tail()
2. {
i becomes 2, 3. int x;
2 < 2 // condition false 4. Node * temp;
Step 14 makes a reference to next of previous element. 5. if (Head = = NULL)
p Tail 6. {
Head 7. printf("\n list empty")
5 10 15
N 8. return ;
9. }
Steps 15 and 16 execute as follows: 10. temp = Head;
p Step 16 N 11. while(temp → next ! = Tail)
Head 12. temp = temp → next;
5 10 15
13. x = Tail → ele;
Step 16 Tail
14. Tail = temp;
20 15. temp = temp → next;
Step 15
temp 16. Tail → next = NULL;
17. printf("\n Deleted element : %d", x)
Now the element 20 becomes the 3rd element in the list.
18. free (temp);
19. }
Deletion Step 4  – Checks for list empty
•• Identify the node Step 10, 11, 12 – Move the temp pointer to last but one
•• Adjust the links, such that deallocation of that node does node of the list
not make the list as unconnected components. Step 13 – Reads tail element to delete
•• Return/display element to delete. Step 14 – Moves tail pointer to last but one
•• Deallocate memory. node
Step 15 – Moves the temp pointer to last node
Delete head element of the list
1. void del _ head() Step 16 – Removes the reference from tail node
2. { to temp node, i.e., tail node becomes
3. int x; the last element
Node * temp; Step 17 – Displays elements to delete
4. if (Head = = NULL) Step 18 – Deallocate memory
3.50 | Unit 3  •  Programming and Data Structures

Delete middle element {


1. void del _ mid (int pos) Node ptr;
2. { ptr = (Node ∗) malloc (size of (struct node)):
3. int i = 1, x; return (ptr);
4. Node * temp P, N; }
5. if(Head = = NULL) If ptr returns NULL, then it is underflow (there is no avail-
6. { able memory) otherwise, it returns start address of memory
7. printf ("\n list empty") location.
8. return;
Search an element
9. }
1. void search (int x)
10. P = head;
2. {
11. while (i < pos -1)
3. Node ∗ temp = head;
12. {
4. int c = 1;
P = P → next;
5. while (temp! = NULL)
i++ ;
6. {
}
7. if (temp → ele = = x)
13. temp = P → next;
8. {
14. N = temp → next;
9. printf("\n Element found at % d”, c);
15. P → next = N;
10. break;
16. x = temp → ele;
11. }
17. printf("\n Element to Delete %d", x);
12. c++;
18. free(temp);
13. }
19. } 14. if (temp = = NULL)
Step 5 – Checks for empty list 15. printf("\n search unsuccessful");
Step 10, 11, 12  – M
 ove previous pointer P to previous 16. }
node of node to delete. Step 7 – Checks temp data with search element.
Step 13 – Temp points to node to delete Repeats this step until the element is
Step 14 – N points to temp next found or reaches the last node
Step 15 – Creates link from P to N Step 9 – Displays the position of search element
Steps 16, 17, 18 – Read and display elements to delete in the list, if found
and deallocate memory. Step 14, 15 – Represents search element not exists in
list
A B C
Display
Node Node.next Node.next.next 1. void display ( )
2. {
3. Node ∗temp = Head;
A B C 4. printf("\n list elements: ");
5. while (temp ! = NULL)
Node Node.next Node.next.next
6. {
7. printf("%d", temp → ele);
Linked list using dynamic variables 8. temp = temp → next;
9. }
Node in the linked list contains data part that is ele and link
10. }
part which points to the next node, and some other external
Step 7 – Displays temp data
pointer will be pointing to this as these take some storage,
Step 8 – Moves temp pointer to next node
a programmer when creating a list, should check with the
available storage. For this we make use of get node () Algorithm to reverse direction of all links of
Function which is defined as follows:
struct node singly liked list
{ Consider a linked list ‘L’ with head as pointer pointing
int ele to the first node contains data element ‘ele’ and a pointer
struct node ∗ next ; called ‘next’ which points to the next node.
}; Reverse is the routine which will reverse the list, there
typedef struct node Node; are three node pointers P, Q, R with P pointing to the first
Node getnode () node, Q pointing to NULL.
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.51

1. START Stack
2. if (P = NULL)
A stack is a last in first out (LIFO) abstract data type and data
1. print (“List is null”);
2. Exit structure. A stack can have any abstract data type as an ele-
3. While (P) ment, but is characterized by only two fundamental operations.
4. R = Q; √ PUSH
5. Q = P; √ POP
6. P = P → next; •• The PUSH operation adds an item to the top of the stack,
7. Q → next = R hiding any items already on the stack or initializing the
8. End While stack if it is empty.
9. Head = Q; •• The POP operation removes an item from the top of the
10. STOP
stack, and returns the poped value to the caller.
•• Elements are removed from the stack in the reverse order to
Double-linked List (DLL)
the order of their insertion. Therefore, the lower elements
Double-linked list is a linked list in which, each node con- are those that have been on the stack for longest period.
tains data part and two link fields.
Node structure:
struct Dnode PUSH POP
{
struct Dnode ∗prev;
int ele;
struct Dnode ∗next;
};
•• prev – points to previous node in list
•• next – points to next node in list Figure 1  Simple representation of a stack
•• The operations which can be performed in SLL can also
be preformed on DLL. Implementation
•• The major difference is that we have to adjust double ref- A stack can be easily implemented either through an array
erence as compared to SLL. or a linked list. The user is only allowed to POP or PUSH
•• We can traverse or display the list elements in forward as items onto the array (or) linked list.
well as in reverse direction.
1. Array Implementation: Array implementation aims
Example: to create an array where the first element inserted is
Tail placed st[0] which will be deleted last.
Head
A B C   The program must keep track of position top (last)
element of stack.
Circular-linked List (CLL) Operations
Initially Top = –1;//represents stack empty
Circular-linked list is completely same as SLL, except, in
(i) Push (S, N, TOP, x)
CLL the last (Tail) node points to first (Head) node of list.
{
So, the Insertion and Deletion operation at Head and Tail
if (TOP = = N – 1)
are little different from SLL.
printf(“overflow”);
else
Double Circular-linked List (DCL)
TOP = TOP + 1;
Double circular-linked list can be traversed in both direc- S[TOP] = x;
tions again and again. DCL is very similar to DLL, except }
the last node’s next pointer points to first node of list and (ii) POP (S, N, TOP, x)
first node’s previous pointer points to last node of list. {
So, the insertion and deletion operations at head and tail if (TOP = = –1)
in DCL are little different in adjusting the reference as com- printf(“underflow”);
pared to DLL. else
Storing ordered table as linked list: The table is stored as x = S[TOP]
a linked list, it is retrieved and stored with two pointers, one TOP = TOP – 1
pointer will point to node holding a record having the smallest return x;
key and other pointer performs the search. }
3.52 | Unit 3  •  Programming and Data Structures

2. Dynamic Implementation: The Array implementa- Steps:


tion is also called static implementation, because the
1. ptr = getNode (Node)
stack size is fixed.
2. ptr.data = item
The stack implementation using linked list is called
3. ptr.next = NULL
dynamic implementation, because the stack size can
4. if (front = NULL)
grow and shrink as the elements added or removed
front = ptr
from the stack.
else
•• The PUSH operation on stack is same as insert
rear.next = ptr;
head in SLL.
5. end if
•• The POP operation is same as delete head in SLL.
6. rear = ptr
Algorithm to add and delete to a link stack and link 7. Stop
queue For deletion of elements from queue that is ptr dequeue ()
Link stack: is given below
Steps:
data 1 data 2
1. if (front = NULL)
1. print “underflow”.
head Top data1 2. exit
2. ptr = front;
The linked stack with head and top pointers is shown 3. front = ptr.next
above 4. Head.next = front
The algorithm to push the elements into stack is given 5. item = ptr.data
below, the method push (item) 6. free(ptr)
Steps: 7. end.

1. ptr = getnode (Node) Uses of Stack


2. ptr.data = item
3. ptr.next = Top •• Function calls: When a function is called all local storage
4. Top = new for the function is allocated on system ‘stack’, and return
5. Head.next = Top address also pushed on to system stack.
6. Stop. •• Recursion stacks can be used to implement recursion if
the programming language does not provide recursion
for deletion of elements from stack, its algorithm is pop(), facility.
it is given below •• Reversing a list
Steps: •• Parsing: Stacks are used by compilers to check the syntax
of program.
1. if (Top = NULL)
•• For evaluating expressions.
1. print “stack is empty”
2. exit Expression Notations
2. Else
Infix expression: Here binary operator comes between the
1. ptr = Top.next
operands.
2. item = Top.data
3. Head.next = ptr Postfix expression: Here the binary operator comes after
4. Top = ptr both the operands.
3. End if Example:  ab+
4. Stop. Prefix expression: Here the binary operator comes before
Linked queue representation both the operands.
Example:  +ab
data1 next data2 datan
Infix to postfix conversion
head front rear •• If operand, output to postfix expression
•• If operator, push it onto stack
The linked queue with head, front and rear point is shown •• In case of parenthesis, when an opening parenthesis is
above. read, it is pushed onto stack and when a closing parenthe-
The algorithm to enqueue the elements into queue is sis is read, all operators up to the first opening parenthesis
given below, the method enqueue (item) must be popped from the stack into the post fix notation.
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.53

Example:  (A + (B – C))*D Algorithm for push A(x)


Initially A[Max], top A = –1, top B = MAX;
i/p Postfix notation Stack
( ( 1. if (top A = top B)
A A ( a. print “ overflow”
+ A (+ b. exit
( A (+( 2. top A = top A + 1
B AB (+( 3. A[top A] = x
- AB (+(–
4. stop
C ABC (+(–
Algorithm for pop A(x)
) ABC– (+
) ABC–+ - 1. if (top A = – 1)
* ABC–+ *
a. print “underflow”
b. exit
D ABC–+D *
2. y = A[top A]
ABC–+D*
3. top A = top A – 1
4. return y
Evaluation of postfix expression
5. stop
We use operand stack for evaluation. Scan the post fix
expression, Algorithm for push B(x)
•• When an operand encounters while scanning, push on to
stack. 1. if (top B – 1 = top A)
•• While scanning post fix expression, if operator found then a. print “overflow”
•• Pop top two operands from stack b. exit
•• Perform the operation on those two operands 2. top B = top B –1
•• Push, result on to stack top 3. A[top B] = x
•• Finally, the stack contains only one value, which repre- 4. stop
sents result of the expression.
Algorithm for pop B(x)
Example:  6 2 3 + – 3 8 2 / + ∗ 2 ∗ 3 +
1. if (top B = max)
Symbol OP1 OP2 Value Operand stack
a. print “underflow”
6 6
b. exit
2 6, 2
2. y = A [top B]
3 6, 2, 3
3. top B = top B – 1
+ 2 3 5 6,5 4. return y
- 6 5 1 5. stop
3 1, 3
8 1, 3, 8
2 1, 3, 8, 2 Queue
/ 8 2 4 1, 3, 4 A queue is an ordered collection of items from which items
+ 3 4 7 1, 7 may be deleted at one end (called that front of queue) and
∗ 1 7 7 7 into which items may be inserted at the other end (called
2 7, 2 rear of queue).
∗ 7 2 14 14 Queue is a linear data structure maintains the data in first
3 14, 3
in−first out (FIFO) order.
+ 14 3 17
Result is 17. Implementation
Queue can be implemented in the following ways:
Performing add, delete operations on stack
(multiple stack) 1. Array static implementation: queue cannot be extended
beyond the array size.
Let us consider an array whose size is ‘max’
2. Linked list dynamic implementation: Queue size
with multiple stack A, B having top A and top B, push and
increases as the elements added/inserted to queue.
pop operations on one stack A is given below.
Queue shrinks when an element deleted from
queue.
3.54 | Unit 3  •  Programming and Data Structures

Array Implementation 6. printf(“Queue Empty”);


const int SIZE = 10; 7. return;
int q[SIZE]; 8. }
int f = –1, r = –1; //f = r = –1 represents queue empty 9. printf (“\n Queue Elemetns”);
10. for(; i < = r; i++)
Front Rear 11. printf(“ %d”, q[i]);
12. }
Step 4 – Checks for ‘q’ empty
Insertion
Step 10 and 11 – Display ‘q’ elements
1. void insert (int x)
2. {
3. if (r = = SIZE –1) Double-ended Queue
4. { A double-ended queue (deque) is an abstract data structure
5. printf(“Q FULL”) that implements a queue for which elements can only be
6. return; added to or removed from the front (head) (or) rear (tail)
7. } end.
8. r++; Rear Rear
9. q[r] = x;
10. if (f = = –1) Front
11. f = r;
12. } Insertions and deletions are possible at both ends.
Step 3 – Checks for queue full
Step 8 – Increments rear (r) Linked List Implementation
Step 9 – Inserts ‘x’ into queue Double-ended Queue
Step 10 – Checks whether insertion is first •• Insert – Front is same as insert – Head
Step 11 – If first insertion, updates front (f) •• Insert – Rear is same as insert – Tail
Deletion •• Delete front is same as delete – Head
1. void deletion() •• Delete – Rear is same as delete – Tail
2. {
3. int x; Circular Queue
4. if (f = = –1)
As the items from a queue get deleted, the space for that
5. {
item is reclaimed. Those queue positions continue to be
6. if (“\n Q Empty”);
empty. This problem is solved by circular queues. Instead
7. return;
of using a linear approach, a circular queue takes a circu-
8. }
lar approach; this is why a circular queue does not have a
9. x = q[f];
beginning or end.
10. if (f = = r)
11. f = r = –1; 1
0 2
12. else
13. f++; 3
14. printf(“\n deleted element %d”, x); 9
15. } 4
Step 4 – Checks for queue empty 8
Step 9 – Deletes ‘q’ front element 5
Step 10 – Checks whether queue having only one element 7
6
Step 11 – Rear and front initializes to –1, if queue is having
only one element The advantage of using circular queue over linear queue is
Step 13 – Queue front points to next element efficient usage of memory.
Step 14 – Deleted element is printed Algorithm to implement addition and deletion from
Display circular queue
1. void display( ) Circular Queue Insertion:
2. { To add an element ‘X’ to a Queue ‘Q’ of size ‘N’ with front
3. int i = f; and rear pointers as ‘F’ and ‘R’ is done with insert (X),
4. if (f = = –1) Initially F = R = 0.
5. { Insert (X)
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.55

Steps: Priority Queue


1. if (((R = N ) & & (F = 1)) or ((R + In priority queue, the intrinsic ordering of elements does
1) = F)) determine the results of its basic operations.
a. print “overflow” There are two types of priority queues.
b. exit
•• Ascending priority queue is a collection of items in which
2. if (R = N)
items can be inserted arbitrarily and from which only the
then R = 0;
smallest items can be removed.
Else
•• Descending priority queue is similar but allows deletion
R = R + 1;
of the largest item.
3. Q[R] = x;
4. if (F = 0) Array Implementation
F = 1
•• The insertion operation on priority queue selects the posi-
5. Stop.
tion to the element to insert.
To delete an element we implement an algorithm delete ().
•• Makes the position empty/free by moving the existing
‘y’ contains the deleted element.
element (if required).
delete() •• Place the element in required position.
Steps: •• Deletion operation simply deletes front of queue.
1. if (F = 0)
a. print “underflow” Linked-list Implementation
b. exit
•• Insertion operation create a node
2. y = Q[F]
•• Reads element into node
3. if (F = R)
•• Find out the location
F = R = 0
•• Insert the node into list, by adjusting the reference
else
•• Deletion operation simply deletes head elements, making
If (F = N)
the head next as head element
F = 1
Else Linked-list Implementation of Priority
F = F + 1
4. Return y
Queue
5. Stop. •• Insertion in queue is same as insert-tail of queue
•• Deletion from queue is same as delete head
Exercises

Practice Problems 1 PUSH(D); POP; POP;


Directions for questions 1 to 16:  Select the correct alterna- PUSH(E)
tive from the given choices. PUSH(F)
POP
1. If the array representation of a circular queue contains
(A) ABE (B) AE
only one element then
(C) A (D) ABCE
(A) front = rear (B) front = rear + 1
(C) front = rear − 1 (D) front = rear = NULL
4. Consider the below code, which deletes a node from
2. The five items P, Q, R, S and T are pushed in a stack, the beginning of a list:
one after another starting from P. The stack is popped void deletefront()
four times, and each element is inserted in a queue. The {
two elements are deleted from the queue and pushed if(head = = NULL)
back on the stack. Now one item is popped from the return;
stack. The popped item is _____. else
(A) P (B) Q {
(C) R (D) S ..........
3. What are the contents of the stack (initially the stack is .........
empty) after the following operations? .........
PUSH (A) }
PUSH (B) }
PUSH (C) Which lines will correctly implement else part of above
POP code?
3.56 | Unit 3  •  Programming and Data Structures

(A) if (head → next = = NULL) next → n = head;


head = head → next; temp → n = NULL;
(B) if (head = = tail) 7. Which of the following program segment correctly
head = tail = NULL; inserts an element at the front of the linked list. Assume
else that Node represents linked list node structure, value is
head = head → next; the element to be inserted.
(C) if (head = = tail = = NULL) (A) temp = (Node ‫)٭‬malloc (sizeof (Node));
head = head → next; temp → data = value;
(D) head = head → next; temp → next = head;
5. When a new element is inserted in the middle of head = temp;
linked list, then the references of _____ to be adjusted/ (B) temp = (Node ‫)٭‬malloc(sizeof (Node‫ )٭‬
updated. );
(A) those nodes that appear after the new node temp → data = value;
(B) those nodes that appear before the new node temp → next = head;
(C) head and tail nodes head = temp;
(D) those nodes that appear just before and after the (C) temp = (Node ‫)٭‬malloc (sizeof (Node));
new node head = temp;
6. The following C function takes double-linked list as an temp → next = head;
argument. It modifies the list by moving the head (first) temp → data = value;
element to tail of the list. (D) temp = (Node ‫)٭‬malloc (sizeof (Node
typedef struct node ‫;)٭‬
{ temp → data = value;
struct node *p; head = temp;
int data; temp → next = head;
struct node *n; 8. Consider the following program segment:
} Node; struct element
Node ⃰ Move – to – last (Node *head) {
{ int x;
Node ⃰ temp, ⃰ prev, ⃰ next; struct element ⃰link;
if (head = = NULL)||(head → n = = NULL)) }
return head; void shuffle(struct element ⃰head)
temp = head; {
prev = head; struct ⃰p, ⃰q;
head = head → n; int t;
while (prev → n! = NULL) if (!head || !head → link) return;
{ p= head ; q = head → link;
X; while(q)
} {
Y; t = p → x;
return head; p→ x = q → x;
} q → x = t;
(A) X: prev = prev → n; p = q → link;
Y: prev → n = temp; q = p? p : 0;
temp → p = prev; }
temp → n = NULL; }
head → P = NULL;
The function called with list containing 10, 15, 20, 25,
(B) X: next = prev → n;
30, 35, 40 in given order. What will the order of ele-
Y: prev → n = temp;
ments of the list, after executing the function shuffle?
temp → p = prev;
(A) 10 15 20 25 30 35 40
(C) X: prev = prev → n;
(B) 40 35 30 25 20 15 10
Y: prev → n = temp;
(C) 20 15 10 25 40 35 30
temp → n = NULL;
(D) 15 10 25 20 35 30 40
head → p = NULL;
(D) X: next = prev → n; 9. Primary ADT’s are
prev = prev → n; (A) Linked list only (B) Stack only
Y: prev → n = Next; (C) Queue only (D) All of these
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.57

10. Linked list uses NULL pointers to signal (C) Both (A) and (B)
(A) end of list (B) start of list (D) None of these
(C) Either (A) or (B) (D) Neither (A) nor (B) 1 4.
Linked list are not suitable for implementing
11. Which of the following is essential for converting an (A) Insertion sort
infix to postfix form efficiently? (B) Binary search
(A) Operator stack (B) Operand stack (C) Radix sort
(C) Both (A) and (B) (D) Parse tree (D) Polynomial manipulation
12. Stacks cannot be used to 15. Insertion of node in a double-linked list requires how
(A) Evaluate postfix expression many changes to previous (prev) and next pointers?
(B) Implement recursion (A) No changes (B) 2 next and 2 prev
(C) Convert infix to postfix (C) 1 next and 1 prev (D) 3 next and 3 prev
(D) Allocate resource like CPU by the operating system 16. Minimum number of stacks required to implement a
3. Linked list can be sorted
1 queue is
(A) By swapping data only (A) 1 (B) 2
(B) By swapping address only (C) 3 (D) 4

Practice Problems 2 (A) Simple queue (B) Circular queue


Directions for questions 1 to 11:  Select the correct alterna- (C) Stack (D) None of these
tive from the given choices. 7. In a circular linked list, insertion of a record involves
1. Stack is useful for implementing _____. the modification of _____.
(A) radix sort (A) no pointer (B) four pointers
(B) breadth first search (C) two pointers (D) All of the above
(C) quick sort 8. Among the following, which one is not the right opera-
(D) recursion tion on a stack?
2. Which is true about linked list? (A) Remove the item that is inserted latest into the
(A) A linked list is a dynamic data structure. stack.
(B) A linked list is a static structure. (B) Add an item to the stack.
(C) A stack cannot be implemented by a linear linked list. (C)  Remove the first item that is inserted into the
(D) None of the above stack, without deleting other elements.
(D) None of the above
3. The process of accessing the data stored in a tape is
similar to manipulating data on a _____. 9. Among the following which one is not the right opera-
(A) stack (B) list tion on dequeue?
(C) queue (D) heap (A) Inserting an element in the middle of a dequeue.
(B) Inserting an element at the front of a dequeue.
4. Which of the following is used to aid in evaluating a
(C) Inserting an element at the rear of a dequeue.
prefix expression?
(D) None of the above
(A) Queue (B) Heap
(C) Stack (D) Hash 10. A linear list in which elements can be added or removed
5. Select the statement which best completes the sentence at either end but not in the middle is _____.
 ‘Abstract data type is…’ (A) queue
(A) a data type which is abstract in nature (B) dequeue
(B) a kind of data type (C) array
(C) data structure (D) tree
(D) a mathematical model together with a set of opera- 11. The post fix notation of A/B * * C + D * E – A * C is
tions defined on it (A) ABC * * /DE * + AC * –
6. Which of the following data structures may give an (B) ABC * * D/E * + AC + –
overflow error, even through the current number of ele- (C) ABC * * /DE * AC + –
ments in it is less than its size? (D) ABC * * /DE * + AC + –
3.58 | Unit 3  •  Programming and Data Structures

Previous Years’ Questions


1. An abstract data type (ADT) is  [2005] int temp;
(A) same as an abstract class. if (!list || !list -> next) return;
(B) a data type that cannot be instantiated. p = list; q = list -> next;
(C) a data type for which only the operations defined while (q) {
on it can be used, but none else. temp = p -> value; p -> value = q ->
(D) All of the above value;
q -> value = temp; p = q → next;
2. An implementation of a queue Q, using two stacks S1 q = p?p -> next : 0;
and S2, is given below: }
void insert (Q, x) { }
  push (S1, x);  [2008]
} (A) 1, 2, 3, 4, 5, 6, 7 (B) 2, 1, 4, 3, 6, 5, 7
void delete (Q) { (C) 1, 3, 2, 5, 4, 7, 6 (D) 2, 3, 4, 5, 6, 7, 1
  if (stack-empty (S2)) then
5. Suppose a circular queue of capacity (n – 1) elements
   if (stack-empty (S1)) then {
is implemented with an array of n elements. Assume
    print (“Q is empty”);
that the insertion and deletion operations are carried
   return;
out using REAR and FRONT as array index vari-
  }
ables, respectively. Initially, REAR = FRONT = 0.
  else while(!(stack-empty(S1)))
The conditions to detect queue full and queue empty
  {
are [2012]
    x = pop (S1);
(A) Full: (REAR + 1) mod n = = FRONT
    push(S2, x);
Empty: REAR = = FRONT
  }
(B) Full: (REAR + 1) mod n = = FRONT
 x = pop (S2);
Empty: (FRONT + 1) mod n = = REAR
}
(C) Full: REAR = = FRONT
Let n insert and m (≤ n) delete operations be per-
Empty: (REAR + 1) mod n = = FRONT
formed in an arbitrary order on an empty queue Q.
(D) Full: (FRONT + 1) mod n = = REAR
Let x and y be the number of push and pop operations
Empty: REAR = = FRONT
performed respectively in the process. Which one of
the following is true for all m and n? [2006] 6. Consider the C program below [2015]
(A) n + m ≤ x < 2n and 2m ≤ y n + m #include <stdio.h>
(B) n + m ≤ x < 2n and 2m ≤ y 2n int *A, stkTop;
(C) 2m ≤ x < 2n and 2m ≤ y n + m int stkFunc (int opcode, int val)
(D) 2m ≤ x < 2n and 2m ≤ y 2n {
static int size=0, stkTop=0;
3. The following postfix expression with single digit
switch (opcode) {
operands is evaluated using a stack:
  case -1: size = val; break;
8 2 3∧ / 2 3 ∗ + 5 1 ∗ –
  case 0: if (stkTop < size)
Note that ∧ is the exponentiation operator. The top
A[stkTop++] =
two elements of the stack after the first ∗ is evaluated
   val; break;
are: [2007]
   default: if (stkTop) return A[-
(A) 6 and 1 (B) 5 and 7
-stkTop];
(C) 3 and 2 (D) 1 and 5
}
4. The following C function takes a single-linked list of return -1;
integers as a parameter and rearranges the elements of }
the list. The function is called with the list containing int main ( )
the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What {
will be the contents of the list after the function com- int B[20]; A = B; stkTop = -1;
pletes execution? stkFunc (-1, 10);
struct node { stkFunc (0, 5);
int value; stkFunc (0, 10);
struct node *next;  printf (“%d\n”, stkFunc(1, 0) +
}; stkFunc(1, 0));
void rearrange (struct node *list) { }
struct node *p, *q; The value printed by the above program is _____
Chapter 4  •  Linked Lists, Stacks and Queues  |  3.59

7. The result of evaluating the postfix expression 10 5 + 9. The attributes of three arithmetic operators in some
60 6/* 8 – is [2015] programming language are given below.
(A) 284 (B) 213
Operator Precedence Associativity Arity
(C) 142 (D) 71
8. Let Q denote a queue containing sixteen numbers and + High Left Binary
S be an empty stack. – Medium Right Binary
Head (Q) returns the element at the head of the queue * Low Left Binary
Q without removing it from Q. Similarly Top(S) The value of the expression
returns the element at the top of S without removing
2 – 5 + 1 – 7 * 3 in this language is ______. [2016]
it from S.
10. A circular queue has been implemented using a sin-
Consider the algorithm given below.
gly linked list where each node consists of a value
and a single pointer pointing to the next node. We
while Q is not Empty do maintain exactly two external pointers FRONT and
if S is Empty OR Top(S) ≤ Head (Q) REAR pointing to the front node and the rear node of
then the queue, respectively. Which of the following state-
x : = Dequeue (Q) ments is/are CORRECT for such a circular queue,
Push (S, x); so that insertion and deletion operations can be per-
else formed in O (1) time?
x : = Pop (S); I. Next pointer of front node points to the rear
enqueue (Q, x); node.
end II. Next pointer of rear node points to the front
end node.
[2017]
The maximum possible number of iterations of the (A) I only (B) II only
while loop in the algorithm is ____ . [2016] (C) Both I and II (D) Neither I nor II

Answer Keys
Exercises
Practice Problems 1
1. A 2. C 3. B 4. B 5. D 6. A 7. A 8. D 9. D 10. A
11. A 12. D 13. C 14. B 15. B 16. B

Practice Problems 2
1. D 2. A 3. C 4. C 5. D 6. A 7. C 8. C 9. A 10. B
11. A

Previous Years’ Questions


1. C 2. A 3. A 4. B 5.  6. 15 7. C 8. 256 9. 9 10. B

You might also like