nth-to-last-node-in-list
2015-07-02 10:58
756 查看
Easy Nth
to Last Node in List
Show result
44%Accepted
Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
Have you met this question in a real interview?
Yes
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) { if(head == null || head.next == null){ return head; } int length = 1; ListNode dummy = head; while(head.next != null){ head = head.next; length++; } int count = 0; head = dummy; while(head != null){ if(count == length-n){ return head; } head = head.next; count++; } return null; } }
相关文章推荐
- nodejs生成vs2008工程问题解决方案
- leetcode Remove Nth Node From End of List 链表 双指针
- 1: installing nodejs
- 2: installing express for nodejs
- 公司项目NODEJS实践0.1
- HADOOP namenode HA
- Configure hexo(node,npm)
- Node.js+Express4.12.4
- GitHub 如何基於 Node.js 和 Chromium 開發 Atom?
- 读《Node.js项目实践:构建可扩展的Web应用》 ——引编程慢慢变成系统化的“砌砖活”...
- 【nodejs】jade模板入门
- Node.js爬虫抓取数据 -- HTML 实体编码处理办法
- Node.js爬虫数据抓取乱码问题总结
- nodejs初学-----helloworld
- Leetcode 117 Populating Next Right Pointers in Each Node II 二叉树填充next指针指向右侧结点 II
- sigaction函数中 SA_NODEFER与sa_mask之间
- Leetcode 116 Populating Next Right Pointers in Each Node 二叉树填充next指针指向右侧结点
- 《转》 Openstack Grizzly 指定 compute node 创建 instance
- hadoop系列 第一坑: hdfs JournalNode Sync Status
- 【nodejs】 npm 注意事项