19. Remove Nth Node From End of List
2017-10-16 15:55
330 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
这道题要求从链表中删除倒数第n个节点,通过两个指针,可以巧妙地在一次遍历中完成删除操作,具体思路如图:
在处理两个指针的时候要小心边界情况,图中加了一个Dummy节点,处理起来更方便。
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个节点,通过两个指针,可以巧妙地在一次遍历中完成删除操作,具体思路如图:
在处理两个指针的时候要小心边界情况,图中加了一个Dummy节点,处理起来更方便。
/** * 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 dummyNode = ListNode(0); ListNode* dummy = &dummyNode; //把DummyNode放在链表开头 dummy->next = head; ListNode* first = dummy; ListNode* second = dummy; for (int i = 0; i < n + 1; i++) { second = second->next; } while (second) { first = first->next; second = second->next; } first->next = first->next->next; //这里注意要返回head,不是dummy return dummy->next; } };
相关文章推荐
- Leetcode[19]-Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List
- 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
- 第二周: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-Java]19. Remove Nth Node From End of List
- Leet Code 19 Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List
- LeetCode(19) Remove Nth Node From End of List
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- 【19】Remove Nth Node From End of List
- LeetCode(19)——Remove Nth Node From End of List
- 19. Remove Nth Node From End of List。