Scarl
Scarl

Reputation: 950

Deleting the second last node from a LinkedList in java

I'm working on a method that is supposed to delete the node prior to the last one,the logic seems quite fine with me, but when I tried to implement it in a project, it didn't work out. ( Oh and I'm using MyLinkedList)

here's the code:

public void deleteSec(){
    Node current = head;
    Node p = head.next;
    Node q = null;

    while(p.next!=null){
        q = current;
        current.next = p;
        p = p.next;
    }
    q.next = p; // q.next = q.next.next;
}

Upvotes: 1

Views: 9270

Answers (4)

YC_
YC_

Reputation: 329

If deleting a second last node would be a common operation, as it is in my case, I would suggest an extra prev or previous node added to the Node construction.

Usually a linked list node would be

private static class Node<Item> {
    private Item item;
    private Node<Item> next;
}

But I modified it to be like

private static class Node<Item> {
    private Item item;
    private Node<Item> prev;
    private Node<Item> next;
}

Thus, if you want to delete the second last, the implementation would be pretty straightforward:

oldSecondLast = last.prev; // Assumes last points to the last node
oldSecondLast.next = last;
last = oldSecondLast.prev;
oldSecondLast = null; // To avoid loitering

Upvotes: 0

Mohammed Alokshiya
Mohammed Alokshiya

Reputation: 643

What if your LL is empty? head will be null and this will cause an exception when you call head.next;

you have to take care of special cases like: empty LL, LL with one node, LL with two nodes.

Here is my code:

public void deleteSec() {
    if (head == null) {
        return;
    }
    if (head.next == null) {
        return;
    }
    if (head.next.next == null) {
        head = head.next;
        return;
    }
    Node current = head;
    Node p = current.next;
    Node q = p.next;
    while (q.next != null) {
        current = current.next;
        p = p.next;
        q = q.next;
    }
    current.next = q;
}

Upvotes: 1

user3241004
user3241004

Reputation: 24

well i personally compiled it,

Assuming the node class is named Node and you have a getNext() method that returns the next Node or null if this Node is the last node, you would do something like this.

if (head == null) // or if (first == null)
{
return; // There are no elements in the list.
}
Node currect = head; // This is the head, or Node current = first;
Node previous = null;
while (current.getNext() != null)
{
previous = current;
currrent = current.getNext();
}

Then do this to make the second to last pointer to next null.
if (previous != null)
{
previous.setNext( null );
}
else
{
// The list has 1 entry only.
head = null; // or first = null;
}

Upvotes: 0

Sully
Sully

Reputation: 14943

if(myLinkedList.size() > 1) {
    myLinkedList.remove(myLinkedList.size()-2);
}

Upvotes: 0

Related Questions