• 面试题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

  • 相关阅读:
    文本框模糊匹配(纯html+jquery简单实现)
    ajax 基础2
    ajax 基础
    Js 实战3(实现全选)
    JS 实战2(邮箱选人功能)
    JS 实战1(添加、删除)
    Js 图片轮播渐隐效果
    Js 手风琴效果
    树上莫队
    洛谷 3676
  • 原文地址:https://www.cnblogs.com/chengpeng15/p/9870527.html
Copyright © 2020-2023  润新知