1、题目
2.1 解法1
@1:思路:计算链表的长度,然后正向找到第L-n个结点
@2:增加哑结点,可以找到需删除结点的前一个结点
@3:变量的合理利用:自减
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// 添加一个哑结点
ListNode dummy = new ListNode(0);
dummy.next = head;
int count= 0;
ListNode temp = head;
while (temp != null) {
temp = temp.next;
count += 1;
}
// 记住自减也可以
count -= n;
temp = dummy;
while (count > 0) {
temp = temp.next;
count -= 1;
}
// 停在前一个结点
temp.next = temp.next.next;
return dummy.next;
}
}
时间复杂度O(2L-n),空间复杂度O(1)
2.2 解法2
@1:使用双指针,first 、second,让两者之间的间隔保证为n+1,直到first == null
@2:因为每次都要next,所以使用哑结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// 添加一个哑结点
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// 因为每次都要next,所以使用哑结点
for (int i = 1; i <= n+1 ; i++){
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
// 停在前一个结点
second.next = second.next.next;
return dummy.next;
}
}
时间复杂度O(L),空间复杂度O(1),因为是常量级别