leetcode 19 删除链表倒数第N个节点

leetcode 19 删除链表倒数第N个节点

一次遍历:

  1. 设置头结点hh,指向head
  2. 双指针pre,cur
  3. pre往前移动n个
  4. 之后pre和cur共同往前移动,直到pre的next为NULL
  5. 返回头指针一定是hh的next(考虑到可能删除的是head)
    leetcode 19 删除链表倒数第N个节点_第1张图片
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* hh=new ListNode (0);
        hh->next=head;
        ListNode* pre=hh;
        ListNode* cur=hh;
        while(n--)
        {
            pre=pre->next;
        }
        while(pre->next!=NULL)
        {
            pre=pre->next;
            cur=cur->next;
        }
        cur->next=cur->next->next;
        return hh->next;
    }
};

你可能感兴趣的:(leetcode 19 删除链表倒数第N个节点)