LeetCode-19-删除链表的倒数第N个节点
题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
解法:
1. 递归解法:
int cur = 0;
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
head.next = removeNthFromEnd(head.next, n);
cur++;
if(n == cur) {
return head.next;
}
return head;
}
运行结果:
2. 快慢指针
利用快慢指针,快指针先走n不,然后快慢指针一起走,当快指针到链表尾部时,slow刚好到n-1的位置。删除slow.next 即可
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || head.next == null) {
return null;
}
// 快慢指针
ListNode fast = head;
ListNode slow = head;
// 先走n步
for(int i = 0; i < n; i++) {
fast = fast.next;
}
// 如果n 是整个链表的长度时,走完n步,fast为null
if (fast == null) {
return head.next;
}
// 快指针走到链表尾部
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
// 删除slow.next 节点
slow.next = slow.next.next;
return head;
}
运行结果:
标题:LeetCode-19-删除链表的倒数第N个节点
作者:guobing
地址:http://www.guobingwei.tech/articles/2020/11/08/1604839592350.html