现在是第二次了,链表的mid题好像相对简单,虽然不是什么很简洁的写法🤪题目链接

解法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//思路,第一次循环计算链表长度,找到待删除节点的前置节点,指向删除节点的后一节点
//注意使用虚拟头节点,不然会产生空指针异常
public static ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null){
return head;
}else if (head.next == null){
return null;
}
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;

ListNode cur = dummyNode;
ListNode cur2 = dummyNode;
ListNode cur3 = cur2;
int size = 0;
while (cur.next != null){
size++;
cur = cur.next;
}
size = size+1;
int index = size-n;
for (int i = 1; i < index; i++) {
cur2 = cur2.next;
}
if (cur2 != null){
cur2.next = cur2.next.next;
}


return cur3.next;

解法二(双指针)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 //by代码随想录
public ListNode removeNthFromEnd(ListNode head, int n){
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;

ListNode fastIndex = dummyNode;
ListNode slowIndex = dummyNode;

// 只要快慢指针相差 n 个结点即可
for (int i = 0; i <= n ; i++){
fastIndex = fastIndex.next;
}

while (fastIndex != null){
fastIndex = fastIndex.next;
slowIndex = slowIndex.next;
}

//此时 slowIndex 的位置就是待删除元素的前一个位置。
//具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
slowIndex.next = slowIndex.next.next;
return dummyNode.next;
}