Please provide a complete and functional Java code to solve

Please provide a complete and functional Java code to solve this problem with comments.

Give an algorithm for finding the second-to-last node in a singly linked list in which the last node is indicated by a null next reference.

Solution

Let\'s suppose there is a class Node defined in the program as follows

class Node {
protected int data;
protected Node next;

public Node() {
data=0;
next=NULL;
}
public void setNext(Node n) {
next=n;
}
public Node getNext() {
return next;
}
public int getData() {
return data;
}
}

Now, take one pointer ptr and move it to the last node.
Node ptr = new Node();
while(ptr.getNext()!=NULL) {
ptr.setNext(ptr.getNext());
}

When it\'s there, take another pointer and move it along the list until its next node is ptr.
Node p = new Node();
while(p.getNext()!=ptr) {
p.setNext(p.getNext());
}

Now the new pointer points to the second last node. You can now print its value
System.out.print(p.getData());

Please provide a complete and functional Java code to solve this problem with comments. Give an algorithm for finding the second-to-last node in a singly linked

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site