Skip to main content

Find second last element in linked list in java

Java program for Find second last element in linked list. Here problem description and other solutions.

// Java program for
// Find the second last node of a linked list

// Node of Linked List
class LinkNode
{
    public int data;
    public LinkNode next;
    public LinkNode(int data)
    {
        // Set node value
        this.data = data;
        this.next = null;
    }
}
public class SingleLL
{
    public LinkNode head;
    public LinkNode tail;
    public SingleLL()
    {
        // Set head and tail 
        this.head = null;
        this.tail = null;
    }
    // Add new node at the end of linked list
    public void insert(int value)
    {
        // Create a new node
        LinkNode node = new LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            this.tail.next = node;
        }
        this.tail = node;
    }
    // Display linked list element
    public void display()
    {
        if (this.head == null)
        {
            return;
        }
        LinkNode temp = this.head;
        // iterating linked list elements
        while (temp != null)
        {
            System.out.print(temp.data + " → ");
            // Visit to next node
            temp = temp.next;
        }
        System.out.print("null\n");
    }
    //Find the second last node of a linked list
    public void secondLast()
    {
        LinkNode node = this.head;
        if (node == null)
        {
            System.out.print("Empty linked list");
        }
        else if (node.next == null)
        {
            System.out.print("Only one node in this linked list");
        }
        else
        {
            // Find second last node
            while (node.next != null && node.next.next != null)
            {
                // Visit to second next node
                node = node.next.next;
            }
            System.out.println("Second last element is : " + node.data);
        }
    }
    public static void main(String[] args)
    {
        SingleLL sll = new SingleLL();
        // Add linked list node
        sll.insert(6);
        sll.insert(3);
        sll.insert(2);
        sll.insert(7);
        sll.insert(1);
        sll.insert(9);
        System.out.println("Linked List");
        // 6 → 3 → 2 → 7 → 1 → 9 → null
        sll.display();
        sll.secondLast();
    }
}

Output

Linked List
6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment