牛客题霸--链表中倒数第k个结点

链表中倒数第k个结点

https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=117&&tqId=34991&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

牛客题霸题目链接:链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=117&&tqId=34991&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

1.使用栈压入,然后取出第k个

public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null) return null;
        if(k<=0) return null;
        Stack<ListNode> st = new Stack<ListNode>();
        while(head!=null){
            st.push(head);
            head=head.next;
        }
        for(int i=1;i<k;i++){
            if(!st.empty()){
                 st.pop();
            }else{
               return null;
            }
        }
        if(!st.empty()){
            return st.peek();
        }
        return null;
    }

2.定义快指针和慢指针
快指针先走 k-1 步,到达第 k 个节点。
然后两指针同时齐步走,当快指针到达末尾时,此时慢指针就在倒数第k个节点上

public ListNode FindKthToTail(ListNode head,int k) {
       if(head==null) return null;
       if(k<=0) return null;
       ListNode fast = head;
       ListNode slow = head;
       for(int i=1;i<k;i++){
           if(fast.next!=null){
               fast=fast.next;
           }else{
               return null;
           }
       }
       while(fast.next!=null){
           fast=fast.next;
           slow=slow.next;
       }
       return slow;
   }
全部评论

相关推荐

竟然收到了测评听说是双机位
投递拼多多集团-PDD等公司10个岗位
点赞 评论 收藏
分享
写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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