找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
/**
* 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 count=0;
ListNode node=head;
while(node!=null){
node=node.next;
count++;
}
if(n>count)
return null;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode node1=dummy;
ListNode node2=dummy;
int i=0;
while(i<=n&&node1!=null){
i++;
node1=node1.next;
}
while(node1!=null){
node1=node1.next;
node2=node2.next;
}
node2=node2.next;
return node2;
}
}