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