zoukankan      html  css  js  c++  java
  • 寻找链表倒数第k个元素,只遍历一遍(编程之美)

    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);
            }
        }
    }
  • 相关阅读:
    软件测试描述错误
    软件测试homework2
    第九次
    第七次作业
    第六次作业
    第五次作业
    第四次作业
    第三次
    软件测试Lab2 Selenium及自动化测试
    软件测试(四)主路径覆盖hw3
  • 原文地址:https://www.cnblogs.com/lindaZ/p/5361622.html
Copyright © 2011-2022 走看看