• 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);
        }
    }
  • 相关阅读:
    js继承《转》
    千分位分割正则
    所有事件失效
    658. Find K Closest Elements
    278. First Bad Version
    153. Find Minimum in Rotated Sorted Array
    11. Container With Most Water
    205. Isomorphic Strings
    75. Sort Colors
    695. Max Area of Island
  • 原文地址:https://www.cnblogs.com/giraffe/p/3210190.html
Copyright © 2020-2023  润新知