我正在尝试删除 LinkedList 中的最后一个节点。 对于输入:1,2,3 输出应该是:1, 2
我可以删除节点,但是有更好/更有效的方法吗?
请检查removeLastNode()
方法。
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;
}
}
}
最佳答案
使用tail
作为最后一个节点。
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;
}
}
关于java - 实现删除链表最后一个节点的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371684/