166. Nth to Last Node in List

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个结点的值。先贴一下自己的代码,思路比较简单,遍历两遍,第一遍算结点总数,推出所求结点是第几个,再遍历一次,得出答案。代码如下:

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param head: The first node of linked list.
17      * @param n: An integer
18      * @return: Nth to last node of a singly linked list. 
19      */
20     public ListNode nthToLast(ListNode head, int n) {
21         // write your code here
22         int number = 0;
23         int count=0;
24         ListNode p = head;
25         while(p != null){
26             number++;
27             p = p.next;
28         }
29         p=head;
30         while(count != (number-n)){
31             count++;
32             p=p.next;
33         }
34         return p;
35     }
36 }

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

 1  public class Solution {
 2      /**
 3       * @param head: The first node of linked list.
 4       * @param n: An integer.
 5       * @return: Nth to last node of a singly linked list.
 6       */
 7      ListNode nthToLast(ListNode head, int n) {
 8          // write your code here
 9          ListNode dummy = new ListNode(0);
10          dummy.next = head;
11          ListNode walker = dummy;
12          ListNode runner = dummy;
13          while (runner.next != null && n>0) {
14              runner = runner.next;
15              n--;
16          }
17          while (runner.next != null) {
18              runner = runner.next;
19              walker = walker.next;
20          }
21          return walker.next;
22      }
23  }

 

转载于:https://www.cnblogs.com/phdeblog/p/9130448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值