I am trying to delete the last node in LinkedList. For the input: 1, 2, 3 Output should be: 1, 2
I am able to delete the node, but is there a better/more efficient way of doing so?
Please check the removeLastNode() method.
public class MyLinkedList {
Node head;
Node tail;
public void add(int number){
Node node=new Node();
node.setNumber(number);
if(head==null){
head=node;
tail=node;
}
else{
tail.next=node;
tail=node;
}
}
public void removeLastNode(){
Node temp=head;
Node head1=null;
Node tail1=null;
while(temp.next!=null){
Node node=new Node();
node.number=temp.number;
if(head1==null){
head1=node;
tail1=node;
}
else{
tail1.next=node;
tail1=node;
}
if(temp.next.next==null){
temp.next=null;
break;
}
temp=temp.next;
}
head=head1;
}
@Override
public String toString(){
while(head!=null){
System.out.print(head.getNumber()+" ");
head=head.getNext();
}
return "";
}
public static void main(String ar[]){
MyLinkedList list=new MyLinkedList();
list.add(1);
list.add(2);
list.add(3);
list.removeLastNode();
System.out.println(list);
}
public class Node{
Node next;
int number;
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
}
Javas classLinkedListimplements aDoubly-linked listby default, it is not a regularlinked list! Thus you already may be good to go with Java'sLinkedList. Or, if you need to implement it by yourself, you can look up how to do it there.