题解 | #链表倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

/*
 for(int i = 0 ; i < n ; i ++) {
                if(i == 0) {
                    root = new Node(sc.nextInt()) ;
                    continue ;
                }
                t.next = new Node(sc.nextInt()) ;
                t = t.next ;  
            }
            sc.nextLine() ;
*/
import java.util.* ;
class Node {
    int val ;
    Node next ;
    Node(int val) {
        this.val = val ;
    }
}
public class Main{
    public static void main(String...args) {
        Scanner sc = new Scanner(System.in) ;
        while(sc.hasNextLine()) {
            int n = sc.nextInt() ;
            sc.nextLine() ;
            Node root = null ;
            Node t = null ;
            String[] arr = sc.nextLine().split(" ") ;
            for(int i = 0 ; i < arr.length ; i ++) {
                int num = Integer.parseInt(arr[i]) ;
                if(i == 0) {
                    root = new Node(num) ;
                      t = root ;
                    continue ;
                }
                t.next = new Node(num) ;
                    t = t.next ;
            }
           
            int k = sc.nextInt() ;
            sc.nextLine() ;
            
           //===============================
            if(k == 0) {
                System.out.println("0") ;
            } else {
                System.out.println(solu(root,k).val) ;
            }
        }
    }
    public static Node solu(Node root , int k) {
        Node fast = root ;
        int c = 0 ;
        //快指针先走k步
        while(fast != null && c < k-1) {
            fast = fast.next ;
            c++ ;
        }
        //考虑链表长度小于k
        if(fast == null) {
            return null ;
        }
        //慢指针在原地
        Node slow = root ;
        //快慢指针同时走,当快指针到达tail结点,那么慢指针刚好在第k个结点
        while(fast.next != null) {
            fast = fast.next ;
            slow = slow.next ;
        }
        return slow ;
        
    }
    
} 

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

今天 00:37
已编辑
山东大学 C++
小浪_Coding:你问别人,本来就是有求于人,别人肯定没有义务免费回答你丫, 有点流量每天私信可能都十几,几十条的,大家都有工作和自己的事情, 付费也是正常的, 就像你请别人搭把手, 总得给人家买瓶水喝吧
点赞 评论 收藏
分享
丿南烟丶:黑白模板吧,不要这样花哨的。 主要成就太空了,和获奖融在一起,写一两行就行了。 职业技能不要这样排,就传统的掌握精通什么什么然后举例补充的一些重要技术点。 自我介绍说实话也没啥用,可以删了。 把自己的两个项目方案细节补充上去,为什么这样设计,怎么设计,成果是什么按star法则来写 你要引导面试官来问你的技能和项目,你的获奖和自我介绍别人可能看都不看一眼或者不太在乎,重要的是展示你能干活的能力
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务