我试图从以下代码中了解为什么头部会被退回。我想它返回null。有人可以解释一下吗?
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;
ListNode fast = head;
ListNode slow = head;
for(int i=0; i<n; i++){
fast = fast.next;
}
//if remove the first node
if(fast == null){
head = head.next;
return head;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
答案 0 :(得分:0)
我认为有一种更好的方法可以从列表末尾删除第n个元素。您可以使用堆栈。将元素放入堆栈中,直至到达末尾。然后,从头开始弹出直到第n个元素。然后,弹出元素的下一个(nth)是下一个。同样,堆栈中的第n个元素的前一个也会窥视。您所需要做的就是将下一个设置为下一个。您需要考虑删除列表的开头和结尾作为边缘情况。另外,您需要考虑空白列表。希望对您有所帮助。
import java.util.Stack;
public class RemoveNthNodeFromLL {
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || (head.next == null)) return null;
Stack<ListNode> s = new Stack<>();
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
prev = curr;
s.push(prev);
curr = curr.next;
}
for (int i = 1; i <= n - 1; i++) {
s.pop();
}
ListNode toBeRemoved = s.pop();
ListNode next = toBeRemoved.next;
if (s.isEmpty()) {
// Removing the head
head = head.next;
} else {
prev = s.peek();
prev.next = next;
}
return head;
}
public static void main(String[] args) {
RemoveNthNodeFromLL r = new RemoveNthNodeFromLL();
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
System.out.println(r.removeNthFromEnd(head, 2));
}
}