zoukankan      html  css  js  c++  java
  • Cracking the coding interview--Q2.2

    Implement an algorithm to find the kth to last element of a singly linked list.

    实现一个算法寻找链表中倒数第K个数..

    解答:

    关于链表的问题,书中也提到了关键的两个技巧,一个是递归;另一个是 The"Runner"Technique,也就是使用两个指针同时遍历链表的方式。这道题可以分别用这两种方法来解决。

    import java.util.HashMap;
    
    public class List {
        int data;
        List next;
    
        public List(int d) {
            this.data = d;
            this.next = null;
        }
    
        public void appendToTail(int d) {
            List end = new List(d);
            List n = this;
            while (n.next != null) {
                n = n.next;
            }
            n.next = end;
        }
    
        public void print() {
            List n = this;
            System.out.print("{");
            while (n != null) {
                if (n.next != null)
                    System.out.print(n.data + ", ");
                else
                    System.out.println(n.data + "}");
                n = n.next;
            }
        }
    
        public int nthToLast(int n) {
            if (this.next == null) {
                if (n == 0)
                    System.out.println(this.data);
                return 0;
            }
            int i = this.next.nthToLast(n) + 1;
            if (i == n)
                System.out.println(this.data);
            return i;
        }
    
        public void nthToLast1(int n) {
            List m = this;
            List pt = this;
            for (int i = 0; i < n; i++){
                if(pt.next == null)
                    return ;
                pt = pt.next;
            }
            while(pt.next != null)
            {
                m = m.next;
                pt = pt.next;
            }
            System.out.println(m.data);
        }
    
        public static void main(String args[]) {
            List list = new List(0);
            list.appendToTail(1);
            list.appendToTail(2);
            list.appendToTail(3);
            list.appendToTail(4);
            list.appendToTail(5);
            list.appendToTail(6);
            list.appendToTail(7);
            list.appendToTail(8);
            list.appendToTail(9);
            list.print();
            list.nthToLast(10);
            list.nthToLast1(10);
        }
    }
  • 相关阅读:
    c++求最大公约数、最小公倍数
    五个简单的shell脚本
    微信小程序slot(一)
    小程序详解子传父
    小程序封装组件详解父传子
    小程序生命周期详解
    小程序之confirm-type改变键盘右下角的内容和input按钮详解
    小程序之按钮你不知道的v2
    小程序image图片缩小不变形
    小程序之navigator跳转方式
  • 原文地址:https://www.cnblogs.com/giraffe/p/3210190.html
Copyright © 2011-2022 走看看