当前位置:网站首页>Leetcode topic resolution remove nth node from end of list

Leetcode topic resolution remove nth node from end of list

2022-06-23 06:16:00 ruochen

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Try to do this in one pass.

In the title n It's legal. , You don't have to n Checked . With the idea of a ruler , The distance between the two pointers is n-1, The last one goes to the end of the table , Then the previous to n 了 .(p by second,q by first)

  1. The pointer p、q Point to the head of the list ;
  2. Move q, send p and q Bad n-1;
  3. Move at the same time p and q, send q To the end of the table ;
  4. Delete p.
public ListNode removeNthFromEnd(ListNode head, int n) {

    if (head == null || head.next == null) {
        return null;
    }

    ListNode first = head;
    ListNode second = head;

    for (int i = 0; i < n; i++) {
        first = first.next;
        if (first == null) {
            return head.next;
        }
    }

    while (first.next != null) {
        first = first.next;
        second = second.next;
    }

    second.next = second.next.next;

    return head;
}
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201141332115065.html