Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Created September 2, 2015 16:59
Show Gist options
  • Select an option

  • Save cxtadment/9667e0929cbc2cc2a0b5 to your computer and use it in GitHub Desktop.

Select an option

Save cxtadment/9667e0929cbc2cc2a0b5 to your computer and use it in GitHub Desktop.
/**
* 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