tag:List
Difficulty:Medium
Problem
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Input: head = [1], n = 1 Output: []
Solutions
解法一:
首先看一种简单的解法。2次遍历链表,统计个数+删除
先统计个数,然后做减法得到要删除的是正数第几个,删除。
注意:count==0代表要删除的是第一个元素,直接返回
public ListNode removeNthFromEnd1(ListNode head, int n) {
ListNode p = head;
int sum = 0;
while (p != null) {
p = p.next;
sum++;
}
int count = sum - n;
if (count == 0) {
return head.next;
}
ListNode pre = head;
p = head.next;
while (count > 1 && p.next != null) {
pre = p;
p = p.next;
count--;
}
pre.next = p.next;
return head;
}
解法二:
能不能遍历一次呢?
遍历一次意味着不要统计了,找到直接删除
因此,需要两个指针遍历链表(比较像快慢指针
首先,p指针向前走n步,如果指向空,说明要删除的是首元素,那么返回head.next即可。
然后,p指针和pre指针同时往前走,直到p为最后一个元素停止,此时pre指向要移除元素的前一个
最后,修改pre指针跳过要移除元素
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head, pre = head;
while (n != 0) {
p = p.next;
n--;
}
if (p == null) {
return head.next;
}
while (p.next != null) {
p = p.next;
pre = pre.next;
}
pre.next = pre.next.next;
return head;
}