![]() |
Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. In this post, methods to insert a new node in a linked list are discussed. A node can be inserted in three ways either at the front of the linked list or after a given node or at the end of the linked list. As we have already discussed Doubly Linked List (DLL) does contain an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in a singly linked list. Similarly, a Triply Linked List (TLL) contains an extra pointer, typically called the top pointer, together with the next pointer, previous, and data which are there in the doubly linked list. The extra pointer here called as the top can be used for various purposes. For example, storing equal values on the same level. Refer to the below image for a better understanding. In this article, we will be inserting nodes in the linked list in sorted order. And we will be storing equal elements on the same level meaning they will be accessed by the top pointer. Illustration: Representation of a DLL node // Class for Triply Linked List public class TLL { // Triply Linked list Node class Node { int data; Node prev; Node next; Node top; } // Head and Tail pointer Node head = null, tail = null; // To keep track of the number // of nodes int node_count = 0; } Procedure: 1. Inserting a new node Since we are storing nodes in a sorted order that’s why we have to find the correct position of the given node in the linked list.
2(A): Traverse the List from Head where we start from the head and keep going to the next node. If the top of the current node is not empty then print the top node first and then continue traversing the rest of the list. 2(B): Traverse the List from Tail or reverse traversal where we start from the tail and keep going to the previous node. If the top of the current node is not empty then print the top node first and then continue traversing the rest of the list. Example: Java
Output
Traversing Linked List head: 1 5 7 top->7 9 Traversing Linked List tail: 9 7 top->7 5 1
|
Reffered: https://www.geeksforgeeks.org
DSA |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |