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  }

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9130448.html