1 of 126

1

2 of 126

2

3 of 126

3

4 of 126

4

DATA STRUCTURES

5 of 126

Array based implementations

  • import array as arr�array1=(2,4,6,7,9)�for x in array1:�    print(x)
  • import array as arr�a=(2,4,6,7,9)�print("first element:",a[0])�print("last element:",a[-1])

5

6 of 126

  • Insert:
  • import array as arr�array1=arr.array('i',[2,3,4,5])�array1.insert(1,60)�for x in array1:�    print(x)

  • last:
  • import array as arr�array1=arr.array('i',[2,3,4,5])�array1.append(8)�print(array1)

6

7 of 126

  • Delete:
  •  import array as arr�array1=arr.array('i',[2,3,4,5])�array1.remove(4)�print(array1)
  •  
  • specified position:
  •  import array as arr�array1=arr.array('i',[2,3,4,5])�array1.pop(2)�print(array1)

7

8 of 126

8

9 of 126

9

10 of 126

10

11 of 126

11

12 of 126

12

13 of 126

13

14 of 126

14

15 of 126

Linked List

  • If arrays accommodate similar types of data types, linked lists consist of elements with different data types that are also arranged sequentially.
  • But how are these linked lists created?
  • A linked list is a collection of “nodes” connected together via links. These nodes consist of the data to be stored and a pointer to the address of the next node within the linked list. In the case of arrays, the size is limited to the definition, but in linked lists, there is no defined size. Any amount of data can be stored in it and can be deleted from it.

15

16 of 126

  • There are three types of linked lists −
  • Singly Linked List − The nodes only point to the address of the next node in the list.
  • Doubly Linked List − The nodes point to the addresses of both previous and next nodes.
  • Circular Linked List − The last node in the list will point to the first node in the list. It can either be singly linked or doubly linked.

16

17 of 126

Linked List Representation

  • Linked list can be visualized as a chain of nodes, where every node points to the next node.

17

18 of 126

  • As per the above illustration, following are the important points to be considered.
  • Linked List contains a link element called first (head).
  • Each link carries a data field(s) and a link field called next.
  • Each link is linked with its next link using its next link.
  • Last link carries a link as null to mark the end of the list.

18

19 of 126

Types of Linked List

  • Following are the various types of linked list.
  • Singly Linked Lists
  • Singly linked lists contain two “buckets” in one node; one bucket holds the data and the other bucket holds the address of the next node of the list. Traversals can be done in one direction only as there is only a single link between two nodes of the same list.

19

20 of 126

Doubly Linked Lists

  • Doubly Linked Lists contain three “buckets” in one node; one bucket holds the data and the other buckets hold the addresses of the previous and next nodes in the list. The list is traversed twice as the nodes in the list are connected to each other from both sides.

20

21 of 126

Circular Linked Lists

  • Circular linked lists can exist in both singly linked list and doubly linked list.
  • Since the last node and the first node of the circular linked list are connected, the traversal in this linked list will go on forever until it is broken.

21

22 of 126

Basic Operations

  • The basic operations in the linked lists are insertion, deletion, searching, display, and deleting an element at a given key. These operations are performed on Singly Linked Lists as given below −
  • Insertion − Adds an element at the beginning of the list.
  • Deletion − Deletes an element at the beginning of the list.
  • Display − Displays the complete list.
  • Search − Searches an element using the given key.
  • Delete − Deletes an element using the given key.

22

23 of 126

Insertion Operation

  • Adding a new node in linked list is a more than one step activity. First, create a node using the same structure and find the location where it has to be inserted.

23

24 of 126

  • Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode). Then point B.next to C −
  • NewNode.next −> RightNode;
  • It should look like this −

24

25 of 126

  • Now, the next node at the left should point to the new node. LeftNode.next −> NewNode;

25

26 of 126

  • This will put the new node in the middle of the two. The new list should look like this −
  • Insertion in linked list can be done in three different ways. They are explained as follows −

26

27 of 126

Insertion at Beginning

  • In this operation, we are adding an element at the beginning of the list.
  • Algorithm
  • 1. START
  • 2. Create a node to store the data
  • 3. Check if the list is empty
  • 4. If the list is empty, add the data to the node and assign the head pointer to it.
  • 5 If the list is not empty, add the data to a node and link to the current head. Assign the head to the newly added node.
  • 6. END

27

28 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class SLL:
  • def __init__(self):
  • self.head = None

28

29 of 126

  • # Print the linked list
  • def listprint(self):
  • printval = self.head
  • print("Linked List: ")
  • while printval is not None:
  • print (printval.data)
  • printval = printval.next
  • def AddAtBeginning(self,newdata):
  • NewNode = Node(newdata)

29

30 of 126

  • # Update the new nodes next val to existing node
  • NewNode.next = self.head
  • self.head = NewNode
  • l1 = SLL()
  • l1.head = Node("731")
  • e2 = Node("672")
  • e3 = Node("63")
  • l1.head.next = e2
  • e2.next = e3
  • l1.AddAtBeginning("122")
  • l1.listprint()

30

31 of 126

  • Linked List:
  • 122
  • 731
  • 672
  • 63

31

32 of 126

Insertion at Ending

  • In this operation, we are adding an element at the ending of the list.
  • 1. START
  • 2. Create a new node and assign the data
  • 3. Find the last node
  • 4. Point the last node to new node
  • 5. END

32

33 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class LL:
  • def __init__(self):
  • self.head = None
  • def listprint(self):
  • val = self.head
  • print("Linked List:")
  • while val is not None:
  • print(val.data)
  • val = val.next

33

34 of 126

  • l1 = LL()
  • l1.head = Node("23")
  • l2 = Node("12")
  • l3 = Node("7")
  • l4 = Node("14")
  • l5 = Node("61")
  • # Linking the first Node to second node
  • l1.head.next = l2
  • # Linking the second Node to third node
  • l2.next = l3
  • l3.next = l4
  • l4.next = l5
  • l1.listprint()

34

35 of 126

Insertion at a Given Position

  • In this operation, we are adding an element at any position within the list.
  • 1. START
  • 2. Create a new node and assign data to it
  • 3. Iterate until the node at position is found
  • 4. Point first to new first node
  • 5. END

35

36 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class SLL:
  • def __init__(self):
  • self.head = None
  • # Print the linked list
  • def listprint(self):
  • printval = self.head
  • print("Linked List: ")
  • while printval is not None:
  • print (printval.data)
  • printval = printval.next

36

37 of 126

  • # Function to add node
  • def InsertAtPos(self,nodeatpos,newdata):
  • if nodeatpos is None:
  • print("The mentioned node is absent")
  • return
  • NewNode = Node(newdata)
  • NewNode.next = nodeatpos.next
  • nodeatpos.next = NewNode
  • l1 = SLL()
  • l1.head = Node("731")
  • e2 = Node("672")
  • e3 = Node("63")
  • l1.head.next = e2
  • e2.next = e3
  • l1.InsertAtPos(l1.head.next, "122")
  • l1.listprint()

37

38 of 126

  • Linked List:
  • 731
  • 672
  • 122
  • 63

38

39 of 126

Deletion Operation

  • Deletion is also a more than one step process. We shall learn with pictorial representation. First, locate the target node to be removed, by using searching algorithms.

  • The left (previous) node of the target node now should point to the next node of the target node −
  • LeftNode.next −> TargetNode.next

39

40 of 126

  • This will remove the link that was pointing to the target node. Now, using the following code, we will remove what the target node is pointing at.
  • TargetNode.next −> NULL

40

41 of 126

  • We need to use the deleted node. We can keep that in memory otherwise we can simply deallocate memory and wipe off the target node completely.

41

42 of 126

  • Similar steps should be taken if the node is being inserted at the beginning of the list. While inserting it at the end, the second last node of the list should point to the new node and the new node will point to NULL.
  • Deletion in linked lists is also performed in three different ways. They are as follows −

42

43 of 126

Deletion at Beginning

  • In this deletion operation of the linked, we are deleting an element from the beginning of the list. For this, we point the head to the second node.
  • Algorithm
  • 1. START
  • 2. Assign the head pointer to the next node in the list
  • 3. END

43

44 of 126

Deletion at Ending

  • In this deletion operation of the linked, we are deleting an element from the ending of the list.
  • Algorithm
  • 1. START
  • 2. Iterate until you find the second last element in the list.
  • 3. Assign NULL to the second last element in the list.
  • 4. END

44

45 of 126

Deletion at a Given Position

  • In this deletion operation of the linked, we are deleting an element at any position of the list.
  • Algorithm
  • 1. START
  • 2. Iterate until find the current node at position in the list
  • 3. Assign the adjacent node of current node in the list to its previous node.
  • 4. END

45

46 of 126

Reverse Operation

  • We need to make the last node to be pointed by the head node and reverse the whole linked list.

  • First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it point to its previous node −

46

47 of 126

  • We have to make sure that the last node is not the last node. So we'll have some temp node, which looks like the head node pointing to the last node. Now, we shall make all left side nodes point to their previous nodes one by one.

47

48 of 126

  • Except the node (first node) pointed by the head node, all nodes should point to their predecessor, making them their new successor. The first node will point to NULL.

48

49 of 126

  • We'll make the head node point to the new first node by using the temp node.

49

50 of 126

  • 1 START
  • 2. We use three pointers to perform the reversing: prev, next, head.
  • 3. Point the current node to head and assign its next value to the prev node.
  • 4. Iteratively repeat the step 3 for all the nodes in the list.
  • 5. Assign head to the prev node.

50

51 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class SLL:
  • def __init__(self):
  • self.head = None

51

52 of 126

  • # Print the linked list
  • def listprint(self):
  • printval = self.head
  • print("Linked List: ")
  • while printval is not None:
  • print(printval.data)
  • printval = printval.next

52

53 of 126

  • def reverse(self):
  • prev = None
  • curr = self.head
  • while(curr is not None):
  • next = curr.next
  • curr.next = prev
  • prev = curr
  • curr = next
  • self.head = prev

53

54 of 126

  • l1 = SLL()
  • l1.head = Node("731")
  • e2 = Node("672")
  • e3 = Node("63")
  • l1.head.next = e2
  • e2.next = e3
  • l1.listprint()
  • l1.reverse()
  • print("After reversing: ")
  • l1.listprint()

54

55 of 126

  • Linked List:
  • 731
  • 672
  • 63
  • After reversing:
  • Linked List:
  • 63
  • 672
  • 731

55

56 of 126

Search Operation

  • Searching for an element in the list using a key element. This operation is done in the same way as array search; comparing every element in the list with the key element given.
  • 1 START
  • 2 If the list is not empty, iteratively check if the list contains the key
  • 3 If the key element is not present in the list, unsuccessful search
  • 4 END

56

57 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class SLL:
  • def __init__(self):
  • self.head = None
  • def search(self, x):
  • count = 0

57

58 of 126

  • # Initialize current to head
  • current = self.head
  • # loop till current not equal to None
  • while current != None:
  • if current.data == x:
  • print("data found")
  • count = count + 1
  • current = current.next
  • if count == 0:
  • print("Data Not found")

58

59 of 126

  • l1 = SLL()
  • l1.head = Node("731")
  • e2 = Node("672")
  • e3 = Node("63")
  • l1.head.next = e2
  • e2.next = e3
  • l1.search("63")

59

60 of 126

  • data found

60

61 of 126

Traversal Operation

  • The traversal operation walks through all the elements of the list in an order and displays the elements in that order.
  • 1. START
  • 2. While the list is not empty and did not reach the end of the list, print the data in each node
  • 3. END

61

62 of 126

  • class Node:
  • def __init__(self, data=None):
  • self.data = data
  • self.next = None
  • class SLL:
  • def __init__(self):
  • self.head = None
  • # Print the linked list
  • def listprint(self):
  • printval = self.head
  • print("Linked List: ")
  • while printval is not None:
  • print (printval.data)
  • printval = printval.next

62

63 of 126

  • l1 = SLL()
  • l1.head = Node("731")
  • e2 = Node("672")
  • e3 = Node("63")
  • l1.head.next = e2
  • e2.next = e3
  • l1.listprint()

63

64 of 126

  • Linked List:
  • 731
  • 672
  • 63

64

65 of 126

Data Structure Doubly Linked List

  • Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward and backward easily as compared to Single Linked List. Following are the important terms to understand the concept of doubly linked list.
  • Link − Each link of a linked list can store a data called an element.
  • Next − Each link of a linked list contains a link to the next link called Next.
  • Prev − Each link of a linked list contains a link to the previous link called Prev.
  • Linked List − A Linked List contains the connection link to the first link called First and to the last link called Last.

65

66 of 126

Doubly Linked List Representation

  • As per the above illustration, following are the important points to be considered.
  • Doubly Linked List contains a link element called first and last.
  • Each link carries a data field(s) and a link field called next.
  • Each link is linked with its next link using its next link.
  • Each link is linked with its previous link using its previous link.
  • The last link carries a link as null to mark the end of the list.

66

67 of 126

Basic Operations

  • Following are the basic operations supported by a list.
  • Insertion − Adds an element at the beginning of the list.
  • Deletion − Deletes an element at the beginning of the list.
  • Insert Last − Adds an element at the end of the list.
  • Delete Last − Deletes an element from the end of the list.
  • Insert After − Adds an element after an item of the list.
  • Delete − Deletes an element from the list using the key.
  • Display forward − Displays the complete list in a forward manner.
  • Display backward − Displays the complete list in a backward manner.

67

68 of 126

Insertion at the Beginning

  • In this operation, we create a new node with three compartments, one containing the data, the others containing the address of its previous and next nodes in the list. This new node is inserted at the beginning of the list.
  • 1. START
  • 2. Create a new node with three variables: prev, data, next.
  • 3. Store the new data in the data variable
  • 4. If the list is empty, make the new node as head.
  • 5. Otherwise, link the address of the existing first node to the next variable of the new node, and assign null to the prev variable.
  • 6. Point the head to the new node.
  • 7. END

68

69 of 126

Deletion at the Beginning

  • This deletion operation deletes the existing first nodes in the doubly linked list. The head is shifted to the next node and the link is removed.
  • 1. START
  • 2. Check the status of the doubly linked list
  • 3. If the list is empty, deletion is not possible
  • 4. If the list is not empty, the head pointer is shifted to the next node.
  • 5. END

69

70 of 126

Insertion at the End

  • In this insertion operation, the new input node is added at the end of the doubly linked list; if the list is not empty. The head will be pointed to the new node, if the list is empty.
  • 1. START
  • 2. If the list is empty, add the node to the list and point the head to it.
  • 3. If the list is not empty, find the last node of the list.
  • 4. Create a link between the last node in the list and the new node.
  • 5. The new node will point to NULL as it is the new last node.
  • 6. END

70

71 of 126

Data Structure - Circular Linked List

  • Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
  • Singly Linked List as Circular
  • In singly linked list, the next pointer of the last node points to the first node.

71

72 of 126

Singly Linked List as Circular

  • In singly linked list, the next pointer of the last node points to the first node.

72

73 of 126

Doubly Linked List as Circular

  • In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions.

73

74 of 126

  • As per the above illustration, following are the important points to be considered.
  • The last link's next points to the first link of the list in both cases of singly as well as doubly linked list.
  • The first link's previous points to the last of the list in case of doubly linked list.

74

75 of 126

Basic Operations

  • Following are the important operations supported by a circular list.
  • insert − Inserts an element at the start of the list.
  • delete − Deletes an element from the start of the list.
  • display − Displays the list.

75

76 of 126

Insertion Operation

  • The insertion operation of a circular linked list only inserts the element at the start of the list.
  • This differs from the usual singly and doubly linked lists as there is no particular starting and ending points in this list.
  • The insertion is done either at the start or after a particular node (or a given position) in the list.

76

77 of 126

  • 1. START
  • 2. Check if the list is empty
  • 3. If the list is empty, add the node and point the head to this node
  • 4. If the list is not empty, link the existing head as the next node to the new node.
  • 5. Make the new node as the new head.
  • 6. END

77

78 of 126

Deletion Operation

  • The Deletion operation in a Circular linked list removes a certain node from the list. The deletion operation in this type of lists can be done at the beginning, or a given position, or at the ending.
  • 1. START
  • 2. If the list is empty, then the program is returned.
  • 3. If the list is not empty, we traverse the list using a current pointer that is set to the head pointer and create another pointer previous that points to the last node.
  • 4. Suppose the list has only one node, the node is deleted by setting the head pointer to NULL.

78

79 of 126

Deletion Operation

  • 5. If the list has more than one node and the first node is to be deleted, the head is set to the next node and the previous is linked to the new head.
  • 6. If the node to be deleted is the last node, link the preceding node of the last node to head node.
  • 7. If the node is neither first nor last, remove the node by linking its preceding node to its succeeding node.
  • 8. END

79

80 of 126

Stack

  • A stack is an Abstract Data Type (ADT), that is popularly used in most programming languages.
  • It is named stack because it has the similar operations as the real-world stacks, for example – a pack of cards or a pile of plates, etc.

  • The stack follows the LIFO (Last in - First out) structure where the last element inserted would be the first element deleted.

80

81 of 126

Stack Representation

  • A Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack.
  • The following diagram depicts a stack and its operations 

81

82 of 126

82

83 of 126

  • A stack can be implemented by means of Array, Structure, Pointer, and Linked List.
  • Stack can either be a fixed size one or it may have a sense of dynamic resizing.
  • Here, we are going to implement stack using arrays, which makes it a fixed size stack implementation.

83

84 of 126

Basic Operations on Stacks

  • Stack operations usually are performed for initialization, usage and, de-initialization of the stack ADT.
  • The most fundamental operations in the stack ADT include: push(), pop(), peek(), isFull(), isEmpty().
  • These are all built-in operations to carry out data manipulation and to check the status of the stack.
  • Stack uses pointers that always point to the topmost element within the stack, hence called as the top pointer.

84

85 of 126

Insertion: push()

  • push() is an operation that inserts elements into the stack. The following is an algorithm that describes the push() operation in a simpler way.
  • 1 − Checks if the stack is full.
  • 2 − If the stack is full, produces an error and exit.
  • 3 − If the stack is not full, increments top to point next empty space.
  • 4 − Adds data element to the stack location, where top is pointing.
  • 5 − Returns success.

85

86 of 126

Deletion: pop()

  • pop() is a data manipulation operation which removes elements from the stack. The following pseudo code describes the pop() operation in a simpler way.
  • 1 − Checks if the stack is empty.
  • 2 − If the stack is empty, produces an error and exit.
  • 3 − If the stack is not empty, accesses the data element at which top is pointing.
  • 4 − Decreases the value of top by 1.
  • 5 − Returns success.

86

87 of 126

  • class Stack:
  • def __init__(self):
  • self.stack = []
  • def __str__(self):
  • return str(self.stack)
  • def push(self, data):
  • if data not in self.stack:
  • self.stack.append(data)
  • return True
  • else:
  • return False
  • def remove(self):
  • if len(self.stack) <= 0:
  • return ("No element in the Stack")
  • else:
  • return self.stack.pop()

87

88 of 126

  • stk = Stack()
  • stk.push(1)
  • stk.push(2)
  • stk.push(3)
  • stk.push(4)
  • stk.push(5)
  • print("Stack Elements:")
  • print(stk)
  • print("----Deletion operation in stack----")
  • p = stk.remove()
  • print("The popped element is: " + str(p))
  • print("Updated Stack:")
  • print(stk)

88

89 of 126

  • Stack Elements:
  • [1, 2, 3, 4, 5]
  • ----Deletion operation in stack----
  • The popped element is: 5
  • Updated Stack:
  • [1, 2, 3, 4]

89

90 of 126

  • peek()
  • The peek() is an operation retrieves the topmost element within the stack, without deleting it. This operation is used to check the status of the stack with the help of the top pointer.
  • 1. START
  • 2. return the element at the top of the stack
  • 3. END

90

91 of 126

  • class Stack:
  • def __init__(self):
  • self.stack = []
  • def __str__(self):
  • return str(self.stack)
  • def push(self, data):
  • if data not in self.stack:
  • self.stack.append(data)
  • return True
  • else:
  • return False
  • # Use peek to look at the top of the stack
  • def peek(self):
  • return self.stack[-1]

91

92 of 126

  • stk = Stack()
  • stk.push(1)
  • stk.push(2)
  • stk.push(3)
  • stk.push(4)
  • stk.push(5)
  • print("Stack Elements:")
  • print(stk)
  • print("topmost element: ",stk.peek())

92

93 of 126

  • Stack Elements:
  • [1, 2, 3, 4, 5]
  • topmost element: 5

93

94 of 126

  • isFull()
  • isFull() operation checks whether the stack is full. This operation is used to check the status of the stack with the help of top pointer.
  • 1. START
  • 2. If the size of the stack is equal to the top position of the stack, the stack is full. Return 1.
  • 3. Otherwise, return 0.
  • 4. END

94

95 of 126

  • isEmpty()
  • The isEmpty() operation verifies whether the stack is empty. This operation is used to check the status of the stack with the help of top pointer.
  • 1. START
  • 2. If the top value is -1, the stack is empty. Return 1.
  • 3. Otherwise, return 0.
  • 4. END

95

96 of 126

Queue

  • Queue, like Stack, is also an abstract data structure.
  • The thing that makes queue different from stack is that a queue is open at both its ends.
  • Hence, it follows FIFO (First-In-First-Out) structure, i.e. the data item inserted first will also be accessed first.
  • The data is inserted into the queue through one end and deleted from it using the other end.

96

97 of 126

  • A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first.
  • More real-world examples can be seen as queues at the ticket windows and bus-stops.

97

98 of 126

Representation of Queues

  • Similar to the stack ADT, a queue ADT can also be implemented using arrays, linked lists, or pointers.
  • We implement queues using a one-dimensional array.

98

99 of 126

Basic Operations

  • Queue operations also include initialization of a queue, usage and permanently deleting the data from the memory.
  • The most fundamental operations in the queue ADT include: enqueue(), dequeue(), peek(), isFull(), isEmpty(). These are all built-in operations to carry out data manipulation and to check the status of the queue.
  • Queue uses two pointers − front and rear. The front pointer accesses the data from the front end (helping in enqueueing) while the rear pointer accesses data from the rear end (helping in dequeuing).

99

100 of 126

  • Insertion operation: enqueue()
  • The enqueue() is a data manipulation operation that is used to insert elements into the stack. The following algorithm describes the enqueue() operation in a simpler way.

100

101 of 126

  • 1 − START
  • 2 – Check if the queue is full.
  • 3 − If the queue is full, produce overflow error and exit.
  • 4 − If the queue is not full, increment rear pointer to point the next empty space.
  • 5 − Add data element to the queue location, where the rear is pointing.
  • 6 − return success.
  • 7 – END

101

102 of 126

  • class Queue:
  • def __init__(self):
  • self.queue = list()
  • def __str__(self):
  • return str(self.queue)
  • def addtoqueue(self,data):
  • # Insert method to add element
  • if data not in self.queue:
  • self.queue.insert(0,data)
  • return True
  • return False

102

103 of 126

  • q = Queue()
  • q.addtoqueue("36")
  • q.addtoqueue("24")
  • q.addtoqueue("48")
  • q.addtoqueue("12")
  • q.addtoqueue("66")
  • print("Queue:")
  • print(q)

103

104 of 126

  • Queue:
  • ['66', '12', '48', '24', '36']

104

105 of 126

  • Deletion Operation: dequeue()
  • The dequeue() is a data manipulation operation that is used to remove elements from the queue.
  • The following algorithm describes the dequeue() operation in a simpler way.

105

106 of 126

  • 1 – START
  • 2 − Check if the queue is empty.
  • 3 − If the queue is empty, produce underflow error and exit.
  • 4 − If the queue is not empty, access the data where front is pointing.
  • 5 − Increment front pointer to point to the next available data element.
  • 6 − Return success.
  • 7 – END

106

107 of 126

  • class Queue:
  • def __init__(self):
  • self.queue = list()
  • def __str__(self):
  • return str(self.queue)
  • def addtoqueue(self,data):
  • # Insert method to add element
  • if data not in self.queue:
  • self.queue.insert(0,data)
  • return True
  • return False
  • def removefromqueue(self):
  • if len(self.queue)>0:
  • return self.queue.pop()
  • return ("Queue is empty")

107

108 of 126

  • q = Queue()
  • q.addtoqueue("36")
  • q.addtoqueue("24")
  • q.addtoqueue("48")
  • q.addtoqueue("12")
  • q.addtoqueue("66")
  • print("Queue:")
  • print(q)
  • print("Element deleted from queue: ",q.removefromqueue())

108

109 of 126

  • Queue:
  • ['66', '12', '48', '24', '36']
  • Element deleted from queue: 36

109

110 of 126

  • The peek() Operation
  • The peek() is an operation which is used to retrieve the frontmost element in the queue, without deleting it. This operation is used to check the status of the queue with the help of the pointer.
  • 1 – START
  • 2 – Return the element at the front of the queue
  • 3 – END

110

111 of 126

  • class Queue:
  • def __init__(self):
  • self.queue = list()
  • def __str__(self):
  • return str(self.queue)
  • def addtoqueue(self,data):
  • # Insert method to add element
  • if data not in self.queue:
  • self.queue.insert(0,data)
  • return True
  • return False
  • def peek(self):
  • return self.queue[-1]

111

112 of 126

  • q = Queue()
  • q.addtoqueue("36")
  • q.addtoqueue("24")
  • q.addtoqueue("48")
  • q.addtoqueue("12")
  • q.addtoqueue("66")
  • print("Queue:")
  • print(q)
  • print("The frontmost element of the queue: ",q.peek())

112

113 of 126

  • Queue:
  • ['66', '12', '48', '24', '36']
  • The frontmost element of the queue: 36

113

114 of 126

  • The isFull() Operation
  • The isFull() operation verifies whether the queue is full.
  • 1 – START
  • 2 – If the count of queue elements equals the queue size, return true
  • 3 – Otherwise, return false
  • 4 – END

114

115 of 126

  • The isEmpty() operation
  • The isEmpty() operation verifies whether the queue is empty. This operation is used to check the status of the stack with the help of top pointer.
  • 1 – START
  • 2 – If the count of queue elements equals zero, return true
  • 3 – Otherwise, return false
  • 4 – END

115

116 of 126

Implementation of Queue

  • class Queue:
  • def __init__(self):
  • self.queue = list()
  • def addtoqueue(self,data):
  • # Insert method to add element
  • if data not in self.queue:
  • self.queue.insert(0,data)
  • return True
  • return False
  • def size(self):
  • return len(self.queue)
  • def removefromqueue(self):
  • if len(self.queue)>0:
  • return self.queue.pop()
  • return ("Queue is empty")

116

117 of 126

Implementation of Queue

  • q = Queue()
  • q.addtoqueue("36")
  • q.addtoqueue("24")
  • q.addtoqueue("48")
  • q.addtoqueue("12")
  • q.addtoqueue("66")
  • print("size of the queue: ",q.size())
  • print("Element deleted from queue: ",q.removefromqueue())
  • print("size of the queue after deletion: ",q.size())

117

118 of 126

  • size of the queue: 5
  • Element deleted from queue: 36
  • size of the queue after deletion: 4

118

119 of 126

Deque

  • A double-ended queue, or deque, has the feature of adding and removing elements from either end.
  • The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.
  • In the below program we import the collections module and declare a deque.
  • Without need of any class we use the in-built implement these methods directly.

119

120 of 126

  • import collections
  • # Create a deque
  • DoubleEnded = collections.deque(["Mon","Tue","Wed"])
  • print (DoubleEnded)
  • # Append to the right
  • print("Adding to the right: ")
  • DoubleEnded.append("Thu")
  • print (DoubleEnded)
  • # append to the left
  • print("Adding to the left: ")
  • DoubleEnded.appendleft("Sun")
  • print (DoubleEnded)

120

121 of 126

  • # Remove from the right
  • print("Removing from the right: ")
  • DoubleEnded.pop()
  • print (DoubleEnded)
  • # Remove from the left
  • print("Removing from the left: ")
  • DoubleEnded.popleft()
  • print (DoubleEnded)
  • # Reverse the dequeue
  • print("Reversing the deque: ")
  • DoubleEnded.reverse()
  • print (DoubleEnded)

121

122 of 126

  • deque(['Mon', 'Tue', 'Wed'])
  • Adding to the right:
  • deque(['Mon', 'Tue', 'Wed', 'Thu'])
  • Adding to the left:
  • deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
  • Removing from the right:
  • deque(['Sun', 'Mon', 'Tue', 'Wed'])
  • Removing from the left:
  • deque(['Mon', 'Tue', 'Wed'])
  • Reversing the deque:
  • deque(['Wed', 'Tue', 'Mon'])

122

123 of 126

123

124 of 126

124

125 of 126

125

126 of 126

126