![]() ![]() Then we will traverse through the list and increment the counter by 1 till we reach the end. So, to do the same with a doubly-linked list, we will simply create a counter and initialize it with 0. In the size() function, we have to return the size of the stack. So, to do the same with a doubly-linked list, we will simply return the head.data. In the top() function, we have to return the top element of the stack. In the end, we will return the head.data that we stored. Now, we will increment the head, and make the prev of head point to Null. ![]() If both the base cases fail, we will store the head.data.If there is only one node in the list, then remove the head, and return None.So, to do the same with a doubly-linked list, first, we will check if the list is Null or not: In the pop() function, we pop the topmost element of the stack and print it. In the end, the new node will become the head. If the list is not empty, then make the prev of head point to the new node, the next of new node point to the head and the prev of new node point to Null.If it is Null, then make the new data the head.So, to do the same with a doubly-linked list, we will check if the list is Null or not: In the push() function, we push the element into the stack, and make it the top. We will learn how each function approaches one by one. Algorithm To Build A Stack Using Doubly Linked List If input is 5 6 7 8, the the doubly linked list having all the functionalities of the stack will be Where the head will be pointing to 1 in the linked list. If our input is 4 3 2 1, then our doubly linked list, which will have all functionalities of a stack, will be ![]() Similarly, we will try to think of other operations such as pop(), top(), etc of stack and how we can implement these operations using doubly linked list. If we can amend the inserting new node operation in doubly linked list such a way that the current inserted element is always at the head of the linked list and is the first element accessible to us if we want to access an element from linked list, then we can see that our linked list is mimicking the behavior of stack.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |