题目:
输入一个链表,输出该链表中倒数第k个结点。
思路:
遍历整个链表,每到一个结点k--,若k不等于0再遍历结点,每到一个结点k++,直到k等于0。
过去提交的通过的答案:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution
{ public ListNode FindKthToTail(ListNode head,int k) { if(head==null||k<1) { return null; } ListNode cur=head; while(cur!=null) { k--; cur=cur.next; } System.out.println("k的值为"+k); cur=head; if(k>0) { return null; } while(k!=0) { ++k; cur=cur.next; } return cur; }
}
再次写一次的答案,带测试用例:
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution01 {
public ListNode FindKthToTail(ListNode head,int k) {
if (head==null||k<=0) {
return null;
}
ListNode p=head;
while(p!=null) {
k--;
p=p.next;
}
if (k>=1) {
return null;
}
ListNode cur=head;
while(k!=0) {
k++;
cur=cur.next;
}
return cur;
}
public static void main(String[] args) {
Solution01 s=new Solution01();
ListNode n1=new ListNode(8);
ListNode n2=new ListNode(7);
ListNode n3=new ListNode(11);
ListNode n4=new ListNode(13);
ListNode n5=new ListNode(243);
ListNode n6=new ListNode(16);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n6;
ListNode res=s.FindKthToTail(n1,3);
System.out.println(res.val);
}
}

京公网安备 11010502036488号