Package problems.geeks.linkedlist

Source Code of problems.geeks.linkedlist.Q001_Get_Nth_Node

package problems.geeks.linkedlist;

/**
* Get Nth node in a Linked List
*
* Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.
*
* Algorithm:
*
* 1. Initialize count = 0
* 2. Loop through the link list
*      a. if count is equal to the passed index then return current
*          node
*      b. Increment count
*      c. change current to point to next of the current.
*     
* 切记,从头往前找第 n 个节点的时候,利用一个计数器来帮助查找,代码会显得比较干净
*/

import java.util.*;

import adt.ListNode;
import adt.LinkedList;

public class Q001_Get_Nth_Node {
 
  static ListNode getNth(ListNode head, int n) {
    if (head == null) {
      return null;
    }
   
    int count = 1;
    ListNode p = head;
   
    while (p != null && count < n) {
      p = p.next;
      count++;
    }
   
    // p 要么是 null,要么就是我们要找的第 n 个
    return p;
  }
 
  public static void main(String[] args) {
    // Initialize a linked list
    LinkedList list = new LinkedList(10);
   
    ListNode node = getNth(list.head, 5);
   
    if (node != null) {
      System.out.println(node.val);
    } else {
      System.out.println("No such node");
    }
  }
 
}
TOP

Related Classes of problems.geeks.linkedlist.Q001_Get_Nth_Node

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.