Open larscheng opened 3 months ago
方法二:双指针,快慢指针间隔n,两个指针一起向后移动,当快指针到达链表尾部时,慢指针即为待更新处
class Solution1 {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0;
ListNode cur = head;
while (cur != null ) {
cur = cur.next;
length++;
}
ListNode dummy = new ListNode(0,head);
cur = dummy;
for (int i = 1; i <= length-n ; i++) {
cur = cur.next;
}
cur.next = cur.next.next;
return dummy.next;
}
}
```java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode slow = dummy;
ListNode fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
19. 删除链表的倒数第 N 个结点