领扣(LeetCode)删除链表的倒数第N个节点 个人题解

给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

快慢针的思想。快针先移动N个步长,然后两个针一起移动,快针结束时,慢针指向倒数第N+1个节点。然后就是简单的删除节点操作了。这里需要注意删除的节点是第一个节点的特判。

这里由于使用了JAVA,对返回head突然有了新的疑惑,为什么操作fast和slow会影响到head的内容。这里需要认真学习一下。

代码如下:

 1 class Solution {
 2     public ListNode removeNthFromEnd(ListNode head, int n) {
 3         if (head == null)
 4             return null;
 5         ListNode slow = head;
 6         ListNode fast = head;
 7         while (n >= 1 && fast.next != null) {
 8             fast = fast.next;
 9             n--;
10         }
11         if (n > 1)
12             return head;
13         if (n == 1)
14             return head.next;
15         while (fast.next != null) {
16             slow = slow.next;
17             fast = fast.next;
18         }
19         slow.next = slow.next.next;
20         return head;
21     }
22 }

猜你喜欢

转载自www.cnblogs.com/axiangcoding/p/10068323.html