remove-nth-node-from-end-of-list
2015-06-11 19:56
543 查看
容易 删除链表中倒数第n个节点
30%通过
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
注意
链表中的节点个数大于等于n
挑战
O(n)时间复杂度
搞半天,两个指针,一个head,一个tail,head走到尾的时候,tail正好走到n+1..
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param n: An integer. * @return: The head of linked list. */ ListNode removeNthFromEnd(ListNode head, int n) { if (0 == n) { return head; } if (head.next == null) { return null; } ListNode p = head; ListNode q = head; while (n != 0) { q = q.next; n--; /* * if n equals to the number of nodes, that means remove the first node, so just let the head to be the head.next. */ // 处理n没有走完的情况,说明链表的长度肯定是<=n,所以移除head if (q.next == null && n != 0) { head = head.next; return head; } } // 处理p后移的问题,保证p和q之间有n个节点,这样移除p之后的一个节点即可 while (q.next != null) { q = q.next; p = p.next; } // 处理移除末尾节点 if (n == 1) { p.next = null; return head; } else { p.next = p.next.next; return head; } } }
相关文章推荐
- NodeJS简单的网页跳转路由demo
- Node.js学习笔记-入门
- nodejs笔记
- NodeSchool——stream-adventure
- 学习老外用webstorm开发nodejs的技巧--代码提示DefinitelyTyped
- 【LeetCode】25.Reverse Nodes in k-Group
- Swap Nodes in Pairs
- nodejs 安装express
- nodejs 学习资料
- nodejs 安装
- nodejs fs.open
- Initialization failed for block pool Block pool <registering> (Datanode Uuid unassigned) service
- Leetcode[222]-Count Complete Tree Nodes
- node.js 标准/错误输出 和 process.exit
- nodejs模块加载机制
- win7下安装node及出现的npm问题
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- LeetCode 之 Swap Nodes in Pairs — C 实现
- 学习nodejs——callback, async i/o
- 【Leetcode Algorithm】Remove Nth Node From End of List