LintCode Nth to Last Node in List 链表倒数第n个节点
2015-06-25 16:24
761 查看
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点1.
Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
Example
Given a List 3->2->1->5->null and n = 2, return node whose value is 1.
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点1.
Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
Example
Given a List 3->2->1->5->null and n = 2, return node whose value is 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: Nth to last node of a singly linked list. */ ListNode nthToLast(ListNode head, int n) { ListNode p = head, q = head; while(n > 0 && p != null) { p = p.next; n--; } while(p != null) { q = q.next; p = p.next; } return q; } }
相关文章推荐
- 在HDFS集群中优化secondary namenode到datanode1节点上,并做重启hdfs集群后,datanode1启动失败
- NodeJS获取命令行后面的参数
- Nodejs服务器管理模块forever
- leetcode-19Remove Nth Node From End of List
- ClippingNode实现跑马灯文字(例如游戏公告等)
- node.js导出excel ,csv
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- Nodepad++ 快捷键
- 写给Node.js新手的7个小技巧
- Count Complete Tree Nodes ——LeetCode
- nodejs学习篇
- kafka I wrote this conflicted ephemeral node
- [NodeJS] 优缺点及适用场景讨论
- 开始刷leetcode day49: Populating Next Right Pointers in Each Node
- Count Complete Tree Nodes
- node-webkit 相关使用心得 --系统托盘(tray)的使用方法
- nodejs笔记1:问题杂记
- Node.js中的process.nextTick使用实例
- [转载]七天学会NodeJS
- [leetcode] Swap Nodes in Pairs