找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
import java.util.Scanner;
/**
* 找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
*
* @author Dell
*
*/
public class Test166 {
public static ListNode nthToLast(ListNode head,int n)
{
if(head==null)
return null;
ListNode p=head;
ListNode q=head;
int count=1;
while(count<n)
{
q=q.next;
count++;
}
while(q.next!=null)
{
p=p.next;
q=q.next;
}
return p;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
ListNode list=new ListNode(-1);
ListNode p=list;
for(int i=1;i<=n;i++)
{
ListNode temp=new ListNode(sc.nextInt());
p.next=temp;
p=p.next;
}
int target=sc.nextInt();
ListNode result=nthToLast(list.next,target);
System.out.println(result.val);
}
}