LeetCode 19. Remove Nth Node From End of List
2016-09-09 21:26
302 查看
描述
给出一条链表,删除从右往左数的第n个节点解决
因为不知道ListNode是如何构成的,所以不考虑删除内存,只是修改了指针。先遍历一遍统计节点个数,然后再利用辅助指针来移动扫描节点的位置。/** * 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) { char buf[sizeof(ListNode)]; ListNode* ptrHead = new(buf) ListNode(-1); ptrHead -> next = head; int cnt = 0; while (head){ ++cnt; head = head -> next; } int pos = cnt - n + 1, cur = 1; if (n == 0 || n > cnt) return NULL; ListNode* now = ptrHead -> next; ListNode* pre = ptrHead; ListNode* post = ptrHead -> next ? ptrHead -> next -> next : NULL; // cout << pos << ' ' << cur << endl; while (now){ if (cur == pos){ pre -> next = post; // cout << pos << ' ' << cur << endl; if (pos == 1){ ptrHead -> next = post; } break; } ListNode* tmp = now; now = now -> next; post = now ? now -> next: NULL; pre = tmp; ++cur; } return ptrHead -> next; } };
相关文章推荐
- [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, Easy] 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
- 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 (2 solutions)
- [Leetcode 19] 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
- 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