Skip to content

Commit 0fe8a75

Browse files
author
刘勋
committed
删除链表的倒数第 n 个节点
1 parent 93d4ca4 commit 0fe8a75

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,19 @@ public static class ListNode {
3030

3131
/**
3232
* 快慢指针遍历连表。看是否相遇。如果相遇在判断是否是循环链表。
33+
* p1=x+y
34+
* p2=x+y+z+y;
35+
* 因为p2是p1的两倍
36+
* 2*(x+y)=x+y+z+y
37+
* x=z
3338
* @param head
3439
* @return
3540
*/
3641
public static ListNode detectCycle(ListNode head) {
3742
if (null== head || head.next==null){
3843
return null;
3944
}
45+
//p1指针走一步、p2指针走两步。如果相等就表示是环形。
4046
ListNode p1=head;
4147
ListNode p2=head;
4248
while(p2!=null && p2.next!=null){
@@ -50,6 +56,7 @@ public static ListNode detectCycle(ListNode head) {
5056
if (p1!=p2){
5157
return null;
5258
}
59+
//p1指向头结点。找到环形入口
5360
p1=head;
5461
while(p1!=p2){
5562
p1=p1.next;

src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public static ListNode removeNthFromEnd(ListNode head, int n) {
3131
if (head.next==null){
3232
return null;
3333
}
34+
//增加一个头部节点,方便删除第一个节点。
3435
ListNode temp=new ListNode(-1);
3536
temp.next=head;
3637
ListNode p1=temp;

0 commit comments

Comments
 (0)