剑指 14. 代码的鲁棒性 链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。
 
本人渣渣思路:要求解链表中的倒数第k个结点,可以采用栈先进后出的特点,倒数第k个进栈的话,出栈的时候就是第k个出栈的了
                          那么一开始就遍历链表,然后将每个结点进栈,在将栈的第k个结点出栈即可

import java.util.Stack;
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {

/*

#以下为错误代码,为什么会错?值得思考一下

Stack<ListNode> stack=new Stack<ListNode>();
while (head!=null) {
stack.push(head);
head=head.next;
}
if(head == null || k ==0 ||k>stack.size()){
return null;
}
ListNode knode = null;
for(int i = 0; i < k; i++){
knode = stack.pop();
}


return knode;
*/

if(head == null || k ==0 ){
return null;
}

//可以先把链表反转,然后找出第k个
Stack<ListNode> stack = new Stack<ListNode>();
int count = 0;
while(head != null){
stack.push(head);
head = head.next;
count++;
}

if(count < k){
return null;
}

ListNode knode = null;
for(int i = 0; i < k; i++){
knode = stack.pop();
}


return knode;
}
}


牛客大佬的神仙代码


代码思路如下:

两个指针,先让第一个指针和第二个指针都指向头结点,

然后再让第一个指正走(k-1)步,到达第k个节点。

然后两个指针同时往后移动,

当第一个结点到达末尾的时候,

第二个结点所在位置就是倒数第k个节点了。。


/*
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<=0){
            return null;
        }
        ListNode pre=head;
        ListNode last=head;       
        for(int i=1;i<k;i++){
            if(pre.next!=null){
                pre=pre.next;
            }else{
                return null;
            }
        }
        while(pre.next!=null){
            pre = pre.next;
            last=last.next;
        }
        return last;
    }
}

猜你喜欢

转载自www.cnblogs.com/Transkai/p/10878128.html