Created
September 2, 2015 16:59
-
-
Save cxtadment/9667e0929cbc2cc2a0b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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. | |
| */ | |
| ListNode nthToLast(ListNode head, int n) { | |
| // write your code here | |
| if (head == null) { | |
| return head; | |
| } | |
| int length = getLength(head); | |
| if (length < n) { | |
| return null; | |
| } | |
| for (int i = 1; i <= length - n; i++) { | |
| head = head.next; | |
| } | |
| return head; | |
| } | |
| private int getLength(ListNode head) { | |
| int size = 0; | |
| while (head != null) { | |
| size++; | |
| head = head.next; | |
| } | |
| return size; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment