给你一个链表, 删除链表的倒数第n个结点, 并且返回链表的头结点.
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
提示:
- 链表中结点的数目为sz
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
思路
暴力解法: 可以先用循环遍历一次链表,获取长度. 再次循环使指针指向要删除的节点的前一个节点进行删除.
双指针法: 创建快指针(right)和慢指针(left), 首先使快指针移动n + 1步, 再让两个指针同时移动, 直到right == null
, 此时慢指针指向的就是要删除的节点的前一个节点.
代码实现
暴力解法:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = getLength(head);
ListNode dummy = new ListNode(-1, head);
ListNode current = dummy;
for(int i = 0; i < length - n; i++) {
current = current.next;
}
current.next = current.next.next;
return dummy.next;
}
public int getLength(ListNode head) {
int length = 0;
while(head != null) {
head = head.next;
length++;
}
return length;
}
}
双指针法:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1, head);
ListNode left = dummy;
ListNode right = dummy;
for(int i = 0; i < n; i++) {
right = right.next;
}
while(right.next != null) {
right = right.next;
left = left.next;
}
left.next = left.next.next;
return dummy.next;
}
}
标签:node,dummy,head,right,ListNode,next,链表,end
From: https://www.cnblogs.com/ahci316/p/17636501.html