Nth to Last Node in List
2016-07-03 03:51
363 查看
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.
分析:
要找到nth to last element,我们需要两个指针,第一个指针先走n步,然后两个指针同时走,知道第一个指针为null.
转载请注明出处:cnblogs.com/beiyeqingteng/
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.
分析:
要找到nth to last element,我们需要两个指针,第一个指针先走n步,然后两个指针同时走,知道第一个指针为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) { if (head == null || n <= 0) return null; ListNode first = head; ListNode last = head; for (int count = 1; count <= n; count++;) { first = first.next; } while(first != null) { first = first.next; last = last.next; } return last; } }
转载请注明出处:cnblogs.com/beiyeqingteng/
相关文章推荐
- Remove Nth Node From End of List
- NodeJS学习历程(2)
- 阿里云服务器搭建ghost博客之Node环境安装(一)
- 提高node性能的奇怪办法
- node.js后台jquery前台-- 实现用户登录注册AJAX交互
- nodejs的module.exports 与 exports
- nodejs学习一
- NodeJS学习历程(1)
- firstChild,nextSibling,childNodes等属性的问题
- node.js跨域请求实现和.net框架的通讯
- leetcode No19. Remove Nth Node From End of List
- 《Nodejs开发加密货币》之二十:关于时间处理的相关问题
- NodeJS 安装
- 51Node 1065----最小正子段和
- 51Node 1035----最长的循环节
- 脚本化文档(1)
- nodejs一文件系统
- Node入门
- node模块系统常用命令
- ZooKeeper的Znode剖析