19. Remove Nth Node From End of List
2016-11-10 19:34
381 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example
死办法。。 有一点要注意, 见下面注释
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int cnt = 0;
int flag = 0;
ListNode* p = head;
if(!head)
return NULL;
if(head->next == NULL && n == 1)
return NULL;
while(head)
{
cnt++;
head = head->next;
}
ListNode* q = p;
while(q)
{
flag++;
if(n == 1) //这里是判断,如果删除的是尾结点,操作会不一样,而且也没有NEXT,直接写next就错了
{
if(flag ==(cnt - n))
q->next = NULL;
}
else
if(flag == (cnt - n + 1))
{
q->val = q->next->val;
q->next = q->next->next;
break;
}
q = q->next;
}
return p;
}
};
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.
死办法。。 有一点要注意, 见下面注释
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int cnt = 0;
int flag = 0;
ListNode* p = head;
if(!head)
return NULL;
if(head->next == NULL && n == 1)
return NULL;
while(head)
{
cnt++;
head = head->next;
}
ListNode* q = p;
while(q)
{
flag++;
if(n == 1) //这里是判断,如果删除的是尾结点,操作会不一样,而且也没有NEXT,直接写next就错了
{
if(flag ==(cnt - n))
q->next = NULL;
}
else
if(flag == (cnt - n + 1))
{
q->val = q->next->val;
q->next = q->next->next;
break;
}
q = q->next;
}
return p;
}
};
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dum(0), *slow=&dum, *fast=head; dum.next=head; //get the dum connected // move the fast pointer according to the offset for(int i=0; i<n; ++i) fast=fast->next; while(fast) { fast=fast->next; slow=slow->next; } //now the slow pointer will be the n+1 th node from the end (may be the dum head) fast=slow->next; slow->next=fast->next; delete fast; //remove the specified node return dum.next; } };
相关文章推荐
- 19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List 对撞指针
- [leetcode]19. Remove Nth Node From End of List@Java解题报告
- Leetcode#19 Remove Nth Node From End of List
- leetcode--19. Remove Nth Node From End of List
- LeetCode 第 19 题 (Remove Nth Node From End of List)
- leetcode 之Remove Nth Node From End of List(19)
- LeetCode19 - remove nth node from end of list
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- leetcode——19——Remove Nth Node From End of List
- 88/19 Merge Sorted Array/Remove Nth Node From End of List(指针运算)
- [LeetCode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- leetcode-Remove Nth Node From End of List-19
- LeetCode---(19)Remove Nth Node From End of List
- LeetCode 19 Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- leetcode刷题(19. Remove Nth Node From End of List)
- [LeetCode]19. Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List