Remove Nth Node From End of List --移除链表中的倒数第k个元素
2014-06-21 23:10
337 查看
问题:链接
Given a linked list, remove the nth node from the end of list and return its head.
For example,
解答:
注意如果移除的元素是头元素的话,需要特别的处理,否则的话直接找到倒数第n+1个元素,移除它后面的元素即可。
代码:
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.
解答:
注意如果移除的元素是头元素的话,需要特别的处理,否则的话直接找到倒数第n+1个元素,移除它后面的元素即可。
代码:
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { int len=0; ListNode *pf = head; while(pf != NULL) { ++len; pf = pf->next; } if(len == n) return head->next; pf = head; ListNode *pl = head; for(int i = 1; i <= n && pf->next != NULL; i++) pf = pf->next; while(pf->next != NULL) { pf = pf->next; pl = pl->next; } pl->next = pl->next->next; return head; } };
相关文章推荐
- [LeetCode] Remove Nth Node From End of List 移除链表倒数第N个节点
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- LeetCode | Remove Nth Node From End of List(移除链表中倒数第n个结点)
- 19. Remove Nth Node From End of List (移除链表倒数第n个节点)
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
- [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
- 面试题15:链表中倒数第k个节点(Leetcode-19:Remove Nth Node From End of List)
- Remove Nth Node From End of List "移除链表中的倒数第N项"
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- 【LeetCode】Remove Nth Node From End of List && 【九度】题目1517:链表中倒数第k个结点
- 【链表&删除倒数第K个节点】Remove Nth Node From End of List
- leetcode 3. 移除链表的倒数第n个节点 Remove Nth Node From End of List
- 19. Remove Nth Node From End of List(移除链表的倒数第n个节点)
- LeetCode-Remove Nth Node From End of List-移除从链表结尾数第n个结点-双指针链表操作
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】