leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
2013-10-21 21:42
831 查看
题目:
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,再删除要求的节点就ok了。
要注意的我觉得应该有两点:
第一如果链表不到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个节点,不改变链表其他节点结构,返回链表头指针。
由于链表是单向的,不能倒着搜索,因此设置两个指针,他们相隔n个节点的距离,同布移动。
当前面的指针到达链表结尾的时候,后面一个指针离结尾的距离正好是n,再删除要求的节点就ok了。
要注意的我觉得应该有两点:
第一如果链表不到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 *left,*right,*Head; right=head; for(int i=0;i<n;++i) { if(!right)return head; right=right->next; } Head=left=new ListNode(-1); Head->next=head; while(right) { right=right->next; left=left->next; } ListNode *t1=left->next,*t2; if(t1)left->next=left->next->next; delete(t1); t2=Head->next; delete(Head); return t2; } }; // blog.csdn.net/havenoidea
题解目录
相关文章推荐
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- 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-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- [Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
- LeetCodet题解--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个节点) 解题思路和方法
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- 174. 删除链表中倒数第n个节点 (remove-nth-node-from-end-of-list)(c++)----lintcode面试题之链表
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)