[LeetCode 题解]: Remove Nth Node From End of List
2014-06-17 14:58
435 查看
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个元素,并返回修改后的链表。
要求: 只经过一次遍历完成上述操作。
经典面试题,找到一个链表的倒数第N个元素的衍伸。 在本题中需要额外的记录第N个元素的上一个元素,用于元素删除。
寻找链表的倒数第N个元素,设置两个指针,分别从链表的头部出发,一个先遍历N个元素, 然后两个指针同时向后遍历,当前一个指针到达链表的尾部时,后一个指针则到达第N个元素。
转载请注明出处 http://www.cnblogs.com/double-win/ 谢谢!
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个元素,并返回修改后的链表。
要求: 只经过一次遍历完成上述操作。
经典面试题,找到一个链表的倒数第N个元素的衍伸。 在本题中需要额外的记录第N个元素的上一个元素,用于元素删除。
寻找链表的倒数第N个元素,设置两个指针,分别从链表的头部出发,一个先遍历N个元素, 然后两个指针同时向后遍历,当前一个指针到达链表的尾部时,后一个指针则到达第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) { ListNode *pre,*first,*last; ListNode ans(0); pre=first=last=head; ans.next=pre; for(int i=0;i<n;i++) first=first->next; //find faster pointer while(first!=NULL) { first=first->next; pre = last; last=last->next; } pre->next = last->next; if(last==head) return head->next; else return ans.next; } };
转载请注明出处 http://www.cnblogs.com/double-win/ 谢谢!
相关文章推荐
- leetcode题解-19. Remove Nth Node From End of List
- leetcode题解-328. Odd Even Linked List && 19. Remove Nth Node From End of List
- [LeetCode]题解(python):019-Remove Nth Node From End of List
- LeetCode题解:Remove Nth Node from End of List
- LeetCode题解——Remove Nth Node From End of List
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- Remove Nth Node From End of List---leetcode 我的java题解
- leetcode 题解 || Remove Nth Node From End of List 问题
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- Leetcode题解 19. Remove Nth Node From End of List
- 【leetcode题解】【E】【61.5】Remove Nth Node From End of List
- leetcode 题解 || Remove Nth Node From End of List 问题
- LeetCode题解(19)--Remove Nth Node From End of List
- LeetCode题解:Remove Nth Node From End of List
- LeetCode 19之Remove Nth Node From End of List的Java题解(三种解法)
- [面试真题] LeetCode:Remove Nth Node From End of List
- leetcode: Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List