LeetCode19 Remove Nth Node From End of List
2016-08-05 22:20
330 查看
题意:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
分析:题目虽然是easy,但是用one pass做起来还是包含几个链表常用的手法的,有参考价值;
链表算法上没有什么难的,就是代码上仔细,再熟悉几种处理方法即可。
1.Two pointers。 利用快慢指针,快指针先走n步,然后一起走,快的下一步到终点了,慢的到达要删除的前一位;
2. dummy node。 凡是head位置可能被删掉,返回出现问题,用dummy node处理返回问题。
代码:
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. Try to do this in one pass. (Easy)
分析:题目虽然是easy,但是用one pass做起来还是包含几个链表常用的手法的,有参考价值;
链表算法上没有什么难的,就是代码上仔细,再熟悉几种处理方法即可。
1.Two pointers。 利用快慢指针,快指针先走n步,然后一起走,快的下一步到终点了,慢的到达要删除的前一位;
2. dummy node。 凡是head位置可能被删掉,返回出现问题,用dummy node处理返回问题。
代码:
/** * 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 dummy(0); dummy.next = head; head = &dummy; ListNode* chaser = head; ListNode* runner = head; for (int i = 0; i < n; ++i) { runner = runner -> next; } while (runner -> next != nullptr) { runner = runner -> next; chaser = chaser -> next; } ListNode* temp = chaser -> next; chaser -> next = chaser -> next -> next; delete temp; return dummy.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