Remove Last Node from the List

Given a Linked List, we need to remove the last node or last element from the List.

Input : 1 -> 2 -> 3 -> 4 -> 5

Output : 1 -> 2 -> 3 -> 4

Straight Forward Approach

1)Check the edge cases

Checking the edge cases is crucial in programming world. It is very important.

Edge cases are:

What happen if head is null? and What happen if next to the head element( is null?

In both the above cases we have to return null😜

2) Removing Last Node

So to remove the last node, we need to know the node which is before to the last node. In our case, 1 -> 2 -> 3 -> 4-> 5, 4 is the node which is before to the last node.

So we have to iterate the loop to point the last node’s beforth position.

Time to cut the last node, at the beforth position of last node, apply the null to the next pointer. Then the connection to the last node cuts off.

Program to Remove Last Node from the List

class ListNode
        public int val;
        public ListNode next;
        public ListNode(int data)
            val = data;
    class Program
        static void Main(string[] args)
            //1 --> 2 --> 3 --> 4 --> 5
            ListNode head = new ListNode(1);
   = new ListNode(2);
   = new ListNode(3);
   = new ListNode(4);
   = new ListNode(5);

            ListNode temp = head;
            Console.WriteLine("Before removing last node from the List");
            while(temp != null)
                temp =;

            //Remove last node from the list, in this case last node is 5
            //Remove 5 from the list

            ListNode newHead = RemoveLastElement(head);
            Console.WriteLine("After removing last node from the List");
            while(newHead != null)
                newHead =;


        private static ListNode RemoveLastElement(ListNode head)
            //1. Edge case
            //when head is null, we need to return null
            if (head == null)
                return head;

            //2. Edge case
            //when is null, then head is the last element, so we need 
              to make the head -> null
            if( == null)
                head = null;
                return head;
                //3. Little Logic
                ListNode tempHead = head;
                while( != null && != null)
                    head =;
       = null;
                return tempHead;

One thought on “Remove Last Node from the List

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s