找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
两个节点中间差n-1个节点,两个一起向后推进,直到后面那个节点的下一个为null,返回前一个就可以了。很简单,注意判断head为空就OK。
/**
* 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 null;
}
ListNode cur = head;
ListNode n_last = head;
for(int i = 0 ; i < n - 1 ; i++){
n_last = n_last.next;
}
while(n_last.next != null){
cur = cur.next;
n_last = n_last.next;
}
return cur;
}
}