Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

remove last node from linked list java

// Java program to remove last node of
// linked list.
class GFG {
 
    // Link list node /
    static class Node {
        int data;
        Node next;
    };
 
    // Function to remove the last node
    // of the linked list /
    static Node removeLastNode(Node head)
    {
        if (head == null)
            return null;
 
        if (head.next == null) {
            return null;
        }
 
        // Find the second last node
        Node second_last = head;
        while (second_last.next.next != null)
            second_last = second_last.next;
 
        // Change next of second last
        second_last.next = null;
 
        return head;
    }
 
    // Function to push node at head
    static Node push(Node head_ref, int new_data)
    {
        Node new_node = new Node();
        new_node.data = new_data;
        new_node.next = (head_ref);
        (head_ref) = new_node;
        return head_ref;
    }


    public static void main(String args[])
    {
        // Start with the empty list /
        Node head = null;
 
        // Use push() function to construct
        // the below list 8 . 23 . 11 . 29 . 12 /
        head = push(head, 12);
        head = push(head, 29);
        head = push(head, 11);
        head = push(head, 23);
        head = push(head, 8);
 
        head = removeLastNode(head);
        for (Node temp = head; temp != null; temp = temp.next)
            System.out.print(temp.data + " ");
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: Simple While Loop Java Example 
Java :: copy linked list 
Java :: java array get index 
Java :: multiple inheritance using interface in java 
Java :: Infinite While Loop Java Example 
Java :: replace all these caracters in string java 
Java :: how to convert errorBody to pojo in retrofit 
Java :: method parameters in java 
Java :: how to put a string in gradle file and acce to it android studio 
Java :: java fields 
Java :: android gridview item click effect ripple 
Java :: Java FileOutputStream to write data to a File 
Java :: Create JDBC connection using properties file 
Java :: ArrayList of prime numbers 
Java :: how to use enumUtils in java 
Java :: type variable java 
Java :: how to return the first character in an array from a method java 
Java :: java check if int is null 
Java :: variables in java 
Java :: android check file extension 
Java :: flutter webview plugin background transparent 
Java :: how to get app categories android packagemanager 
Java :: if not java 
Java :: convert stringbuffer to string in java 
Java :: java string equals null 
Java :: display 2d array 
Java :: UPLOAD TEXTFILE USING CYPERTEXT USING JAVA 
Java :: how to make a rest api in spring 
Java :: enhanced for loop arraylist 
Java :: java jbutton get background color 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =