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

  • 相关阅读:
    java 编译
    MapReduce
    搜索引擎中index、attribute和summary概念
    正排索引和倒排索引简单介绍
    SVN 使用
    PlantUML + Chrome 联合使用
    vim 多标签和多窗口
    关于数据库不适合docker的原因(摘抄)
    跨域
    is_valid校验机制
  • 原文地址:https://www.cnblogs.com/chengpeng15/p/9870527.html
Copyright © 2011-2022 走看看