The Wayback Machine - https://web.archive.org/web/20240725081851/https://www.geeksforgeeks.org/java-program-to-implement-triply-linked-list/
Open In App

Java Program to Implement Triply Linked List

Last Updated : 10 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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.

  1. If there are no nodes in the list ( List is empty ), then just make the head and tail point to this node.
  2. If the given node is less than the head node, then just insert the node at the beginning.
  3. If the given node is not less than the head node, then traverse the list and find the first node that is greater than the given node.
    • If such a node doesn’t exist this means that the given node is greater than all the nodes. So insert it to the end of the List.
    • If such a node does exist then insert the given node before the found node.
    • If the given node is equal to some already present node then insert the given node to the top of the 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




// Java Program to Implement Triply Linked List
 
// Importing all utility classes
import java.util.*;
 
// Main Class
public class GFG {
 
    // First let us create a Node class
    class Node {
 
        // Data refers to the value in node
        int data;
 
        // Being triply linked list,
        // three pointers needs to be defined
        Node prev;
        Node next;
        Node top;
 
        // Parameterized constructor of Node class
        // to initialize the node whenever created
        Node(int data)
        {
 
            // this keyword refers to current object itself
            this.data = data;
 
            // Initializing all 3 pointers to null
            prev = null;
            next = null;
            top = null;
        }
    }
 
    // Defining two new pointers for iterate over to perform
    // operations over the triply linked list Head and Tail
    // pointer
    Node head = null, tail = null;
 
    // Declaring and initializing variable to
    // keep track of the number of nodes
    int node_count = 0;
 
    // Method 1
    // To insert a new node
    public void insert(int new_data)
    {
 
        // Create new node with the given data
        Node new_node = new Node(new_data);
 
        // curr_node to traverse the List
        Node curr_node = null;
 
        // If List is empty then
        // make head and tail
        // equal to this node
        if (node_count == 0) {
 
            // Case 1: Of LinkedList is empty
            // If there is no such node existing
            tail = new_node;
            head = new_node;
            curr_node = head;
 
            // So next will be assigned a null
            curr_node.next = null;
            curr_node.prev = null;
            curr_node.top = null;
 
            // Increment the node count
            node_count++;
        }
 
        // Case 2: If LinkedList is not empty
 
        // Case 2(A): If given node is less than the head
        else {
 
            // Make curr_node point to head
            curr_node = head;
 
            // If given node is less than the head
            // insert at the beginning
            if (new_node.data < curr_node.data) {
 
                // Linking two nodes through addresses
                new_node.next = curr_node;
                curr_node.prev = new_node;
                new_node.prev = null;
                head = new_node;
                curr_node = head;
 
                // Adjusting the tail
                do {
 
                    curr_node = curr_node.next;
                } while (curr_node.next != null);
                tail = curr_node;
            }
 
            // CAse 2(B): If given node is not less than the
            // head
            else {
 
                // last_node to keep track of
                // the last visited node
                Node last_node = curr_node;
 
                // Goal is to traverse the List and
                // find first node greater than new_node
                while (curr_node != null
                       && new_node.data > curr_node.data) {
                    last_node = curr_node;
                    curr_node = curr_node.next;
 
                    // If curr_node is null that
                    // means we have reached the
                    // end of the list so insert the
                    // node at the end and update the tail
                    if (curr_node == null) {
 
                        last_node.next = new_node;
                        new_node.prev = last_node;
                        new_node.next = null;
                        tail = new_node;
 
                        // Haulting the execution of the
                        // program using break keyword
                        break;
                    }
 
                    else if (new_node.data
                             <= curr_node.data) {
 
                        // If curr_node is greater than
                        // the new_node then insert the
                        // new_node before curr_nod and
                        // update the tail
                        if (new_node.data
                            < curr_node.data) {
 
                            last_node.next = new_node;
                            new_node.prev = last_node;
                            new_node.next = curr_node;
                            curr_node.prev = new_node;
                            if (curr_node.next != null) {
 
                                do {
 
                                    curr_node
                                        = curr_node.next;
                                }
 
                                while (curr_node.next
                                       != null);
                            }
 
                            tail = curr_node;
 
                            break;
                        }
 
                        // If curr_node is equal to the
                        // new_node then insert the
                        // new_node to the top of the
                        // curr_nod and update the tail
                        else if (curr_node.data
                                 == new_node.data) {
                            last_node = curr_node;
                            while (last_node.top != null) {
 
                                last_node = last_node.top;
                            }
 
                            last_node.top = new_node;
                            new_node.top = null;
 
                            break;
                        }
                    }
                }
            }
        }
    }
 
    // Method 2
    // Traversing list from head
    public void traverse_head()
    {
 
        Node node = head;
        Node curr = null;
 
        while (node != null) {
            System.out.print(node.data + "\t");
            curr = node;
 
            // If curr has top node
            // then traverse them first
            while (curr.top != null) {
                curr = curr.top;
 
                // Print top node first followed by rest of
                // list
                System.out.print("top->" + curr.data
                                 + "\t");
            }
 
            // Update the node to next node
            node = node.next;
        }
 
        // New line
        System.out.println();
    }
 
    // Method 3
    // Traversing list from tail
    public void traverse_tail()
    {
 
        Node node = tail;
        Node curr = null;
 
        while (node != null) {
 
            System.out.print(node.data + "\t");
            curr = node;
 
            // If curr has top node
            // then traverse them first
            while (curr.top != null) {
 
                curr = curr.top;
 
                // Print top node first followed by rest of
                // list
                System.out.print("top->" + curr.data
                                 + "\t");
            }
 
            // Update the node to prev node
            node = node.prev;
        }
 
        // New line
        System.out.println();
    }
 
    // Method 4
    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of main class in the main()
        // method
        //  by starting with the empty list
        GFG tll = new GFG();
 
        // Inserting custom input integer numbers
        // using insert() method
        // Number Set = {7,9,1,5,7}
 
        // Insert the first number i.e 7,
        // so linked list become
        // 7 -> NULL
        tll.insert(7);
 
        // Insert the second number i.e 9,
        // so linked list becomes
        // 7 -> 9 -> NULL
        tll.insert(9);
 
        // Insert the third number i.e 1,
        // so linked list becomes
        // 1 -> 7 -> 9 -> NULL
        tll.insert(1);
 
        // Insert the fourth number i.e 5,
        // so linked list becomes
        // 1 -> 5 -> 7 -> 9 -> NULL
        tll.insert(5);
 
        // Insert the fifth number i.e 7,
        // so linked list becomes
        // 1 -> 5 -> 7 (top->7) -> 9 -> NULL
        tll.insert(7);
 
        // Display message only
        System.out.println(
            "\nTraversing Linked List head: ");
 
        // Calling the traverse_head() method () / Method 2
        tll.traverse_head();
 
        // Display message only
        System.out.println(
            "\nTraversing Linked List tail: ");
 
        // Calling the traverse_tail() method / Method 3
        tll.traverse_tail();
    }
}


Output

Traversing Linked List head: 
1    5    7    top->7    9    

Traversing Linked List tail: 
9    7    top->7    5    1    

The representation of workflow the linked list after running the above program is pictorially depicted and is as follows:

 



Similar Reads

Java Program to Implement Unrolled Linked List
An Unrolled Linked List is a special type of Linked List in which each node stores an array of elements, unlike a simple linked list. Here we use an ArrayList and a constructor that initializes the size of the Unrolled Linked List. Elements are added to the first Node until it is filled and then a new Node is created with the same size. The Node cl
5 min read
Java Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The
3 min read
Can We Implement Xor Linked List in Java?
As we all can depict from the below figure that doubly LinkedList requires two link fields in order to store the address of the next node and the address of the right node Right? So XOR Linked list Typically acts as Doubly LinkedList. Each node of XOR Linked List requires only a single pointer field which doesn't actually store the actual memory ad
3 min read
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Hash Tables(similar to tables in general) provide a subset of the dynamic set operations. Usually, a set of keys are mapped with some values based on certain relations. However, there might be situations when different keys map to the same position provided by the Hash function, which leads to a collision. One of the ways to overcome this situation
5 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The
3 min read
Implement a stack using singly linked list
To implement a stack using the singly linked list concept, all the singly linked list operations should be performed based on Stack operations LIFO(last in first out) and with the help of that knowledge, we are going to implement a stack using a singly linked list. So we need to follow a simple rule in the implementation of a stack which is last in
15 min read
Java Program to Implement Hash Table Chaining with List Heads
A hash table is a data structure that executes a connected array, it is a structure that maps keys to its values. It uses a hash function to calculate an index position for the keys, also called hash code. It will store key and value pair in an array of buckets, and from that bucket, the values can be easily found with the help of keys. To find the
4 min read
Java Program to Implement Adjacency List
Adjacency List is the data structure used to represent graphs which can consist of the vertices(nodes) and the edges(connections between the nodes). In the adjacency list, each vertex is associated with the list of its neighbouring vertices. This data structure is most commonly used to efficiently represent sparse graphs where the number of edges i
4 min read
Program to implement Run Length Encoding using Linked Lists
Given a Linked List as the input. The task is to encode the given linked list using Run Length Encoding. That is, to replace a block of contiguous characters by the character followed by it's count. For Example, in Run Length Encoding "a-&gt;a-&gt;a-&gt;a-&gt;a" will be replaced by "a-&gt;5". Note: For non-repeating nodes, do not append count 1. Fo
15+ min read
Java Program to Implement Control Table in Java
Control tables will be tables that control the control stream or have a significant influence on program control. There are no unbending guidelines about the structure or substance of a control table—its passing trait is its capacity to coordinate the control stream somehow or another through "execution" by a processor or mediator. The plan of such
3 min read
Practice Tags :
three90RightbarBannerImg