[LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
2014-06-30 17:06
267 查看
Remove Nth Node From End of List
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个节点的位置?
办法:用两个指针p,q。让p指针先前进n步。再让p,q同步前移。这样就形成了一个跨度为n的“刻度尺”。就能方便找出倒数第n个节点。
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.
Note:
Given n will always be valid.
Try to do this in one pass.
题目要求:只能用一趟遍历,这是题目的关键。
分析:
关键问题:单向链表如何才能找到倒数第n个节点的位置?
办法:用两个指针p,q。让p指针先前进n步。再让p,q同步前移。这样就形成了一个跨度为n的“刻度尺”。就能方便找出倒数第n个节点。
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode *p=head,*q=head; while(n--){ p=p->next; } //此时p与q已经相差n步 if(p==NULL){ //表示要删的头结点,n与链表的长度一样长 head=head->next; return head; } while(p->next!=NULL){ p=p->next; q=q->next; } //次时q->next 就是需要被删除的节点 q->next=q->next->next; return head; } };
相关文章推荐
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- [Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- Remove Nth Node From End of List 删除链表倒数第N个节点
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- leetcode 3. 移除链表的倒数第n个节点 Remove Nth Node From End of List
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- [LeetCode] Remove Nth Node From End of List 移除链表倒数第N个节点
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- 174. 删除链表中倒数第n个节点 (remove-nth-node-from-end-of-list)(c++)----lintcode面试题之链表