原题链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn2925/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next == null)
return null;
ArrayList<ListNode> a = new ArrayList<ListNode>();
int i = 1;
ListNode pre = head;
while(pre.next != null)
{
a.add(pre);
pre = pre.next;
i++;
}
if(i<=n){
head.val = head.next.val;
head.next = head.next.next;
}else{
pre = a.get(i-n-1);
pre.next = pre.next.next;
}
return head;
}
}
硬生生把链表题做成了ArrayList数组题 (¦3」∠)
下面贴一下leetcode官方“一趟扫描”正确解法
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}