Badar Shahzad Khan Badar Shahzad Khan - 26 days ago 9
Java Question

Unable to delete last node in linked list

I trying to delete the last node from my singly-linked list. But I am still unable to resolve this error in code. My

deleteFromEnd
method is not removing the last node. After calling the delete method, it's still showing the node that I want to delete. The rest of the list is deleted, but the last node itself is not removed. Can you tell me what I am missing, or where the error is?

LinkedList:

package lab5;

public class LinkedList {

public static void main(String argsp[]) {
List ob = new List();

ob.addAtStart("y", 6);
ob.addAtStart("w", 4);
ob.addAtStart("z", 3);

ob.addAtEnd("a", 3);
ob.addAtEnd("b", 4);
ob.addAtEnd("c", 5);

/*
* ob.display(); System.out.println("Deleted first one");
* ob.deleteFromStart();
*/
ob.display();
System.out.println("Deleted End one");
ob.deleteFromEnd();
ob.display();
}
}


List:

package lab5;

public class List {

Node head;

public List() {
head = null;
}

public List(Node e) {
head = e;
}

Node oldfirst = null;
Node lasthead = null;

public void addAtStart(String name, int age) {
Node newObject = new Node(name, age);
newObject.next = head;

if (oldfirst == null) {
oldfirst = newObject;
}
head = newObject;
lasthead = head;

}

public void display() {
Node store = head;
while (store != null) {
store.display();
store = store.next;
System.out.println();
}
}

public void addAtEnd(String name, int age) {
Node atEndValue = new Node(name, age);
oldfirst.next = atEndValue;
oldfirst = atEndValue;
}

public void deleteFromStart() {
if (head.next != null) {
head = head.next;
}
}

public void deleteFromEnd() {
Node start = head;
Node prev = null;
while (head != null) {
prev = head;
head = head.next;
}
prev.next = null;
head = prev;
}

public Node search(String name) {
return head;
}

public boolean isEmpty() {
return head == null;
}

public int size() {
return (head.toString()).length();
}
}


Node:

package lab5;

public class Node {

String name;
int age;
Node next;

public Node() {
name = "Abc";
age = 10;
next = null;
}

public Node(String name, int age) {
this.name = name;
this.age = age;
next = null;
}

public void display() {
System.out.println("Name: " + name + " Age: " + age);
}
}

Answer

You are modifying head pointer of list which is wrong. Following method worked for me.

public void deleteFromEnd() {
        Node start = head;
        Node prev = null;
        while (start.next != null) {
            prev = start;
            start = start.next;
        }
        prev.next = null;
    }
Comments