首页 > 代码库 > 删除倒数第N个节点

删除倒数第N个节点

19. Remove Nth Node From End of List

 1 class Solution { 2 public: 3     ListNode* removeNthFromEnd(ListNode* head, int n) { 4         ListNode *dimmy=new ListNode(0);//加入头结点使得编程简单 5         dimmy->next=head; 6         ListNode *p=dimmy,*q=dimmy; 7         int i=1; 8         while(q->next&&i<=n){ 9             q=q->next;10             i++;11         }12         while(q->next){13             p=p->next;14             q=q->next;15         }16         ListNode *k=p->next;17         p->next=k->next;18         delete k;19         return dimmy->next;20     }21 };

 

删除倒数第N个节点