zoukankan      html  css  js  c++  java
  • 剑指offer 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;
        }
    }
  • 相关阅读:
    什么是 bean 的自动装配?
    什么是 Spring 的内部 bean?
    什么是 Spring 的 MVC 框架?
    Spring AOP and AspectJ AOP 有什么区别?
    解释 JDBC 抽象和 DAO 模块?
    volatile 类型变量提供什么保证?
    一个 Spring Bean 定义 包含什么?
    什么是 Spring MVC 框架的控制器?
    使用 Spring 访问 Hibernate 的方法有哪些?
    什么是 Callable 和 Future?
  • 原文地址:https://www.cnblogs.com/Transkai/p/10878128.html
Copyright © 2011-2022 走看看