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;
}
}
}
Add a Node previous
attribute to the Node
and a Node last
to LinkedList to get a DoubleLinkedList.
Then you can do something like
Node temp = List.getLast().getPrevious(); //returns the second last item
List.removeLast(); //sets the last item to null
List.setLast(temp); //sets the last item to the second last item
List.getLast().setNext(null);
Use that tail
is the last node.
public void removeLastNode() {
if (head == null) {
throw new IllegalStateException();
}
if (head == tail) {
head = null;
tail = null;
} else {
Node current = head;
while (current.next != tail) {
current = current.next;
}
current.next = null;
tail = current;
}
}
Yes You can delete last node from linked list by tracking previous node.
public int deleteAtLast() {
if (head == null) {
return 0;
} else {
Node prevoursNode = null;
Node n = head;
while (n.next != null) {
prevoursNode=n;
n = n.next;
}
int data = n.data;
prevoursNode.next=null;
return data;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.