Remove Nth Node From End of List 删除链表的倒数第n个结点

来源:互联网 发布:照片贴图软件 编辑:程序博客网 时间:2024/06/06 09:00
/**
 * 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 dummy(-1);
      dummy.next=head;
      ListNode *prev=&dummy;
      ListNode *p=head;
      ListNode *q=head;
      for(int i=0;i<n;i++)
      {
          p=p->next;
      }
      
      while(p!=NULL)
      {
          prev=q;
          p=p->next;
          q=q->next;
          
      }
      prev->next=q->next;
      ListNode *temp=q;
      delete q;
    return dummy.next;
    }
};
0 0