Description

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.

解题:给一个链表,求倒数第n个结点的值。先贴一下自己的代码,思路比较简单,遍历两遍,第一遍算结点总数,推出所求结点是第几个,再遍历一次,得出答案。代码如下:

 /**
* 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.
*/
public ListNode nthToLast(ListNode head, int n) {
// write your code here
int number = 0;
int count=0;
ListNode p = head;
while(p != null){
number++;
p = p.next;
}
p=head;
while(count != (number-n)){
count++;
p=p.next;
}
return p;
}
}

再贴一下另一中解法,稍微绕个弯子就可以了。定义两个游标,保证前一个与后一个差n,前一个到尾的时候,后一个就是所求值。代码如下:

  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) {
// write your code here
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode walker = dummy;
ListNode runner = dummy;
while (runner.next != null && n>0) {
runner = runner.next;
n--;
}
while (runner.next != null) {
runner = runner.next;
walker = walker.next;
}
return walker.next;
}
}

最新文章

  1. linux下flash的安装
  2. 事件冒泡和事件捕获以及解释target和currenttarget的区别
  3. 再读GFS论文
  4. 剑指Offer 替换空格
  5. BZOJ 1475 & 1324 && 建图最小割
  6. 一个鼠标键盘控制两台甚至多台主机的方法--Synergy
  7. ssl https服务 需要 php5.3以上
  8. python之SQLAlchemy ORM 上
  9. Insertion Sort List Leetcode
  10. [js高手之路]Node.js+jade+express+mongodb+mongoose+promise实现todolist
  11. L1正则化及其推导
  12. ActiveMQ的运用
  13. 【Storm篇】--Storm基础概念
  14. 移除Windows图标快捷方式小箭头
  15. 关于ajaxFileUpload图片上传,success和error都触发的情况
  16. react创建项目很慢,最后提示fetch failed的解决方法
  17. 关于Retrofit网络请求URL中含有可变参数的处理
  18. 牛客网_Go语言相关练习_选择题(1)
  19. 第一章:初识Python
  20. Flex 得到一个对象的所有属性

热门文章

  1. 使用Scanner将InputStream类型转换成String
  2. 不推荐在iOS的浏览器应用上使用click和mouseover
  3. Notes 20180307 : 运算符
  4. Swift_继承
  5. 持续集成(CI – Continuous Integration)
  6. CentOS中的 yum upgrade 和 yum update 的区别
  7. 关于“CheckBox”通过表单提交的问题
  8. Apache常规配置说明
  9. 记一次PHP实现接收邮件信息(我这里测试的腾讯企业邮件)
  10. 安装cronsun管理定时脚本