寻找链表倒数第k个元素,只遍历一遍(编程之美)

本文介绍了一种仅需遍历一次链表即可找到倒数第K个元素的方法。通过让快指针先向前移动K步,然后慢指针从头开始移动,当快指针到达链表尾部时,慢指针恰好指向倒数第K个元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class LNode
{
    public LNode next;
    public int data;
}
/*找出倒数第k个元素,只遍历一遍*/
class Kk
{
    private static LNode head = new LNode();;
    private static LNode node;
    private static LNode tail;
    private static LNode fast;
    private static LNode slow;
    private static int index;
    private static int k;
    public static void main(String[] args){
        int[] nums = {1,2,3,4,5,6,7,8,9,10}; 
        head.data = nums[0];
        tail = head;
        createLine(nums);
        printLine();
        
        //假设要找的倒数K为4,也就是7
        //让fast先走K步,随后slow跟上,同步后移,当fast到达最后,slow的位置就是倒数K
        k=4;
        fast = head;
        for (int i=0;i<4 ;i++ )
        {
            fast = fast.next;
            System.out.println("fast开始:"+fast.data);
        }
        
        //当fast到达第K个元素,slow就从第一个元素开始
        slow = head.next;

        while (fast!=null&&fast.next!=null)
        {
            fast = fast.next;
            System.out.println("fast="+fast.data);
            slow = slow.next;
            System.out.println("slow="+slow.data);
        }

        System.out.println("链表的倒数第"+k+"个元素是:"+slow.data);

    }

    private static void createLine(int[] nums){
        while (index<10)
        {
            node = new LNode();
            tail.next = node;
            node.data = nums[index];
            node.next = null;
            tail = node;
            index ++;
            
        }
    }

    private static void printLine(){
        node = head;
        while(node!=null&&node.next!=null){
            node = node.next;
            System.out.println(node.data);
        }
    }
}

 

转载于:https://www.cnblogs.com/lindaZ/p/5361622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值