LeetCode:Remove Nth Node From End of List
2015-02-23 23:10
190 查看
很常规的题目,但稍不留神就容易出错,有这么几种情况需要注意:
1)删除的结点正好是第一个结点
2)删除的结点正好是最后一个结点
PS:由于链式存储结构的内存空间不一定是连续的,千万不要用p++,要记得用p=p->next到达下一个结点
/** * 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 *p,*q,*pre; int i; if(head->next==NULL&&n==1) { head=NULL; return head; } p=head; q=head; pre=head; for(i=0;i<n;i++) { q=q->next; } while(p&&q) { if(p!=head) pre=pre->next; p=p->next; q=q->next; } if(p==head) head=p->next; else pre->next=p->next; free(p); return head; } };
相关文章推荐
- leetcode -- Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 解题报告
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 笔记系列四 Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- [leetcode]Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [leetcode刷题系列]Remove Nth Node From End of List
- leetcode--Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List