zoukankan      html  css  js  c++  java
  • 面试题15:链表中倒数第K个结点

    输入一个链表,输出该链表中倒数第k个结点。

    方法1:

    这个解法要循环两次链表

    /*
    public class ListNode {
        int val;
        ListNode next = null;
     
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution1 {
        public ListNode FindKthToTail(ListNode list,int k) {
            if (list == null)   return list;
    
            ListNode node = list;
            int count = 0;
            while (node != null) {
                count++;
                node = node.next;
            }
            if (count < k)  return null;
    
            ListNode p = list;
         //走n-k步
    for (int i = 0; i < count - k; i++) { p = p.next; } return p; } }

    方法2:快慢指针

    /*
    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 slow = head;
            ListNode fast = head;
    
            //fast指针先走k-1步
            for (int i=0;i<k-1;i++){
                if(fast.next==null){
                    return null;
                }else {
                    fast = fast.next;
                }
            }
            while (fast.next!=null){
                fast=fast.next;
                slow=slow.next;
            }
            return slow;
        }
    
    }

     可以参考单链表成环 https://www.cnblogs.com/chengpeng15/p/9868109.html

  • 相关阅读:
    伸展树(SplayTree)的实现
    map的访问
    #pragma warning(disable 4786)
    debian sftp/ssh197
    debian 配置静态ip197
    deepin 安装tar.gz197
    npm构建vue项目197
    linux 常用命令197
    application/force-download 不生效197
    reids 安装197
  • 原文地址:https://www.cnblogs.com/chengpeng15/p/9870527.html
Copyright © 2011-2022 走看看