LeetCode Solution 04: 19Remove Nth Node From End of List
2015-05-28 16:35
656 查看
Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.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.
Note:
Given n will always be valid.
Try to do this in one pass.
从后往前数,删除第N个数
一开始想的比较简单,后来发现各种情况都有,比如,删除头,删除尾,删除中间,都是不一样的
提示出错之后修改了一下,通过
/** * 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) { if (head->next == NULL) return NULL; else { int length = 0; ListNode * len = head; while (len) { length++; len = len->next; } if (length == n) { head = head->next; return head; } else { ListNode * p = head; ListNode * p2 = head; int position = length - n; for (int i = 1; i < position; i++) { p = p->next; p2 = p2->next; } p = p->next; if (p->next==NULL) { p2->next = NULL; return head; } else { p2->next = p->next; delete p; return head; } } } } };
相关文章推荐
- 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
- 1.1数组和链表:19. Remove Nth Node From End of List(Leetcode)
- leetcode-Remove Nth Node From End of List-19
- leetcode 19 Remove Nth Node From End of List
- leetcode19~Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- leetcode19: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:M-19. Remove Nth Node From End of List
- 【LeetCode】19 Remove Nth Node From End of List (c++实现)
- 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】C# 19、Remove Nth Node From End of List