How do you remove the last element in a linked list?

Remove last node of the linked list

Given a linked list, the task is to remove the last node of the linked list and update the head pointer of the linked list.

Examples:

Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL Output: 2 -> 4 -> 6 -> 8 -> 33 -> NULL Explanation: The last node of the linked list is 67, so 67 is deleted.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: To delete the last node of a linked list, find the second last node and make the next pointer of that node null.

Algorithm:



1. If the first node is null or there is only one node, then they return null.

if headNode == null then return null if headNode.nextNode == null then free head and return null

2. Create an extra space secondLast, and traverse the linked list till the second last node.

while secondLast.nextNode.nextNode != null secondLast = secondLast.nextNode

3. delete the last node, i.e. the next node of the second last node delete(secondLast.nextNode), and set the value of the next second-last node to null.

Implementation:




// CPP program to remove last node of

// linked list.

#include <iostream>

using namespace std;

/* Link list node */

struct Node {

int data;

struct Node* next;

};

/* Function to remove the last node

of the linked list */

Node* removeLastNode(struct Node* head)

{

if (head == NULL)

return NULL;

if (head->next == NULL) {

delete head;

return NULL;

}

// Find the second last node

Node* second_last = head;

while (second_last->next->next != NULL)

second_last = second_last->next;

// Delete last node

delete (second_last->next);

// Change next of second last

second_last->next = NULL;

return head;

}

// Function to push node at head

void push(struct Node** head_ref, int new_data)

{

struct Node* new_node = new Node;

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

}

// Driver code

int main()

{

/* Start with the empty list */

Node* head = NULL;

/* Use push() function to construct

the below list 8 -> 23 -> 11 -> 29 -> 12 */

push(&head, 12);

push(&head, 29);

push(&head, 11);

push(&head, 23);

push(&head, 8);

head = removeLastNode(head);

for (Node* temp = head; temp != NULL; temp = temp->next)

cout << temp->data << " ";

return 0;

}




// 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;

}

// Driver code

public static void main(String args[])

{

// Start with the empty list /

Node head = null;

// Use push() function to con

// 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 + " ");

}

}

// This code is contributed by Arnab Kundu




# Python3 program to remove the last node of

# linked list.

import sys

import math

# Link list node

class Node:

def __init__(self, data):

self.data = data

self.next = None

# Function to push node at head

def push(head, data):

if not head:

return Node(data)

temp = Node(data)

temp.next = head

head = temp

return head

# Function to remove the last node

# of the linked list

def removeLastNode(head):

if head == None:

return None

if head.next == None:

head = None

return None

second_last = head

while(second_last.next.next):

second_last = second_last.next

second_last.next = None

return head

# Driver code

if __name__=='__main__':

# Start with the empty list

head = None

# Use push() function to con

# 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)

while(head):

print("{} ".format(head.data), end ="")

head = head.next

# This code is contributed by Vikash kumar 37




// C# program to remove last node of

// linked list.

using System;

class GFG {

// Link list node /

public class Node {

public int data;

public 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;

}

// Driver code

public static void Main(String[] args)

{

// Start with the empty list /

Node head = null;

// Use push() function to con

// 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)

Console.Write(temp.data + " ");

}

}

/* This code contributed by PrinciRaj1992 */




<script>

// javascript program to remove last node of

// linked list. // Link list node /

class Node {

constructor() {

this.data = 0;

this.next = null;

}

}

// Function to remove the last node

// of the linked list /

function removeLastNode(head)

{

if (head == null)

return null;

if (head.next == null) {

return null;

}

// Find the second last node

var 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

function push(head_ref , new_data)

{

var new_node = new Node();

new_node.data = new_data;

new_node.next = (head_ref);

(head_ref) = new_node;

return head_ref;

}

// Driver code

// Start with the empty list /

var head = null;

// Use push() function to con

// 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 (temp = head; temp != null; temp = temp.next)

document.write(temp.data + " ");

// This code contributed by Rajput-Ji

</script>

Output: 8 23 11 29

Complexity Analysis:

  • Time Complexity: O(n).
    The algorithm involves traversal of the linked list till its end, so the time complexity required is O(n).
  • Space Complexity: O(1).
    No extra space is required, so the space complexity is constant.

How do you remove the last element in a linked list?




Article Tags :

Data Structures

Linked List

Technical Scripter

Technical Scripter 2018

Practice Tags :

Data Structures

Linked List

LinkedList removeLast() Method in Java

The Java.util.LinkedList.removeLast() method is used to remove the last element from the LinkedList. This method also returns the element after removing it.
Syntax:

LinkedList.removeLast()

Parameters: This function does not take any parameters.
Return Value: The method returns the last element or the element present at the tail of the list.
Below program illustrate the Java.util.LinkedList.removeLast() method:




// Java code to illustrate removeLast()

import java.io.*;

import java.util.LinkedList;

public class LinkedListDemo {

public static void main(String args[])

{

// Creating an empty LinkedList

LinkedList<String> list = new LinkedList<String>();

// Use add() method to add elements in the list

list.add("Geeks");

list.add("for");

list.add("Geeks");

list.add("10");

list.add("20");

// Displaying the list

System.out.println("LinkedList:" + list);

// Remove the tail using removeLast()

System.out.println("The last element is removed: " + list.removeLast());

// Displaying the final list

System.out.println("Final LinkedList:" + list);

// Remove the tail using removeLast()

System.out.println("The last element is removed: " + list.removeLast());

// Displaying the final list

System.out.println("Final LinkedList:" + list);

}

}

Output: LinkedList:[Geeks, for, Geeks, 10, 20] The last element is removed: 20 Final LinkedList:[Geeks, for, Geeks, 10] The last element is removed: 10 Final LinkedList:[Geeks, for, Geeks]

Time complexity of removeLast() : O(1)

How do you remove the last element in a linked list?

Article Tags :

Java

Java - util package

Java-Collections

Java-Functions

java-LinkedList

Practice Tags :

Java

Java-Collections

Remove Last In Linked List

easy

Prev Next

Try First, Check Solution later

1. You should first read the question and watch the question video.
2. Think of a solution approach, then try and submit the question on editor tab.
3. We strongly advise you to watch the solution video for prescribed approach.

1. You are given a partially written LinkedList class.
2. Here is a list of existing functions:
2.1 addLast - adds a new element with given value to the end of Linked List
2.2. display - Prints the elements of linked list from front to end in a single line.
All elements are separated by space
2.3. size - Returns the number of elements in the linked list.
2.4. removeFirst - Removes the first element from Linked List.
2.5. getFirst - Returns the data of first element.
2.6. getLast - Returns the data of last element.
2.7. getAt - Returns the data of element available at the index passed.
2.8. addFirst - adds a new element with given value in front of linked list.
2.9. addAt - adds a new element at a given index.
3. You are required to complete the body of removeLast function. This function should remove the last element and update appropriate data members. If the size is 0, should print "List is empty". If the size is 1, should set both head and tail to null.
4. Input and Output is managed for you.Input FormatInput is managed for youOutput FormatOutput is managed for youQuestion Video

Comment