描述
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
Example 1:
Input: list = 3->2->1->5->null, n = 2
Output: 1
Example 2:
Input: list = 1->2->3->null, n = 3
Output: 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.
*/
public ListNode nthToLast(ListNode head, int n) {
// write your code here
if(head==null){
return null;
}
ListNode store=head;
for(int i=0;i<n;i++){
head=head.next;
}
while(head!=null){
head=head.next;
store=store.next;
}
return store;
}
}
错误代码
import java.lang.*;
public class Solution {
public static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public static ListNode nthToLast(ListNode head, int n) {
// write your code here
if(head==null){
return null;
}
if(head.next==null&&n==1){
return head;
}
ListNode store=head;
for(int i=0;i<n;i++){
if(head.next!=null){
System.out.println(head.val);
head=head.next;
continue;
}
else{
return null;
}
}
while(head!=null){
head=head.next;
store=store.next;
}
return store;
}
public static void main(String[] args) {
ListNode a=new ListNode(-1);
ListNode head=a;
a.next=new ListNode(0);
a=a.next;
a.next=new ListNode(1);
a=a.next;
a.next=new ListNode(3);
ListNode ans=nthToLast(head,4);
System.out.print(ans.val);
}
}