sweet1cris

Untitled

Jan 9th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition for ListNode.
  4.  * public class ListNode {
  5.  *     int val;
  6.  *     ListNode next;
  7.  *     ListNode(int val) {
  8.  *         this.val = val;
  9.  *         this.next = null;
  10.  *     }
  11.  * }
  12.  */
  13. public class Solution {
  14.     /**
  15.      * @param head: The first node of linked list.
  16.      * @param n: An integer.
  17.      * @return: Nth to last node of a singly linked list.
  18.      */
  19.     ListNode nthToLast(ListNode head, int n) {
  20.         if (head == null || n < 1) {
  21.             return null;
  22.         }
  23.    
  24.         ListNode p1 = head;
  25.         ListNode p2 = head;
  26.         for (int j = 0; j < n - 1; ++j) {
  27.             if (p2 == null) {
  28.                 return null;
  29.             }
  30.             p2 = p2.next;
  31.         }
  32.         while (p2.next != null) {  
  33.             p1 = p1.next;  
  34.             p2 = p2.next;
  35.         }
  36.         return p1;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment