Basic

This part we will talk about some classic date structure and algorithm.
First, we all know binary search:

/**
     * Return the index of the array whose a[index] is equal to key
     * Return -1 if not found 
     * @param key
     * @param a
     * @return
     */
    public static int rank(int key,int[] a){
        int lo=0;
        int hi=a.length-1;
        while(lo<=hi){
            int mid=(lo+hi)/2;
            if(key<a[mid])      hi=mid-1;
            else if(key>a[mid]) lo=mid+1;
            else return mid;
        }
        return -1;
    }

Here we take the array as int. The time complexity is O(logn).

Second, as it happens, it was a question asked by an interviewer. How to make the array random. Actually he asked not like this, he gave me a group people with their own gifts. All they want exchange gift with each other, please find a way to make the progress as random as possible. On the other hand, after exchanging, no one get his own gift.

public static void shuffle(int[] a){
        int N=a.length;
        for(int i=0;i<N-1;i++){
            //Exchange a[i] with the random element in a[i+1...N-1]
            int r=i+1+(int)((N-i-1)*Math.random());
            int temp=a[i];
            a[i]=a[r];
            a[r]=temp;
        }
    }

I call it as shuffle, the main idea is exchange a[i] with the a[i+1...].
Attention! if

    int r=i+(int)((N-i)*Math.random());

we can also shuffle, but maybe some can get his own gift as
(int)((N-i)*Math.random())==0

Third, how a simple stack data structure be constructed? Here is a stack with fixed size:

import java.util.Iterator;
//What the difference of Iterable and Iterator
public class FixedCapacityStackOfStrings implements Iterable<String> {
    private String[] a;//stack entries
    private int N=0;//size
    //Initialize
    public FixedCapacityStackOfStrings(int capSize){
        a = new String[capSize];
    }
    
    public boolean isEmpty(){
        return N==0;
    }
    
    public int size(){
        return N;
    }
    
    //what if N>=a.length?
    public void push(String item){
        a[N++]=item;
    }
    
    public String pop(){
        return a[--N];
    }
    
    public String toString(){
        String s="";
        for(String e:a){
            s+=e+" ";
        }
        return s;
    }
    
//Iterator
    @Override
    public Iterator<String> iterator() {
        return new HelpIterator();
    }
    
    private class HelpIterator implements Iterator<String>{
        private int i=N;
        public boolean hasNext(){return i>0;}
        public String next(){return a[--i];}
        public void remove(){ }
    }   
    
    /**
     * Test unit
     * @param args
     */
    public static void main(String[] args) {
        FixedCapacityStackOfStrings test=new FixedCapacityStackOfStrings(5);
        test.push("hello");
        test.push("you");
        test.push("panic");
        System.out.println("first");
        for(String e:test)
        System.out.println(e);
        test.pop();
        System.out.println("second:");
        for(String e:test)
            System.out.println(e);
    }
    
}

The main operations are pop, push and the iterator. You can test it with your own test case. After overflow it'll break.

Fourth, how to construct a stack which can adjust size as the change of the number of element:


import java.util.Iterator;

public class ResizingArrayStack<Item> implements Iterable<Item> {

    private Item[] a = (Item[]) new Object[1];//Stack item
    private int N=0;//Number of stack
    
    public boolean isEmpty(){ return N==0;}
    public int size(){return N;}
    
    //See the Item[] size
    public int ItemSize(){return a.length;}
    
    private void resize(int max){
        //Move stack to a new array of size max
        Item[] temp= (Item[]) new Object[max];
        //Copy
        for(int i=0;i<N;i++)
            temp[i]=a[i];
        a=temp;
    }
    
    public void push(Item item){
        //Add item to the top of stack
        if(N==a.length) resize(2*a.length);
        a[N++]=item;
    }
    
    public Item pop(){  
        //Remove the top of the stack
        Item item=a[N--];
        a[N]=null;//??
        if(N>0 && N==a.length/4) resize(a.length/2);
        return item;
    }
    
    public String toString(){
        String s="";
        for(Item e:a){
            s+=e+" ";
        }
        return s;
    }
    
//Iterator methods  
    @Override
    public Iterator<Item> iterator() {
        return new helpIterator();
    }
    
    public class helpIterator implements Iterator<Item>{
        //Support the LILO iteraion
        private int i=N;
        public boolean hasNext(){return i>0;   }
        public Item next()      {return a[--i];}
        public void remove()    {              }
    }
    
    /**
     * Test unit
     * @param args
     */
    public static void main(String[] args) {
        ResizingArrayStack<Integer> test=new ResizingArrayStack<>();
        //Push
        for(int i=0;i<15;i++){
        test.push(i);
        System.out.println(test);
        System.out.println(test.ItemSize());
        }
        //Pop
        while(!test.isEmpty()){
            test.pop();
            System.out.println(test);
            System.out.println(test.ItemSize());
        }
    }

}

The main idea is resize, new an array and copy the date from old to new. The same idea occur in many places.

Fifth, we can see that the above way to construct stack is based on array, so what if with Linked-list?


import java.util.Iterator;

public class Stack<Item> implements Iterable<Item> {
    //The stack is based on Linked-list
    private class Node{
        Item item;
        Node next;
    }
    
    private Node top;
    private int N;//The number of the elements
    
    public boolean isEmpty(){
        return top==null;//or return N==0
    }
    public int size(){
        return N;
    }
    
    public void push(Item item){
        //Add the item to the top of stack
        Node oldTop=top;
        top=new Node();
        top.item=item;
        top.next=oldTop;
        N++;
    }
    
    public Item pop(){
        //Remove item from the top of stack
        Node oldTop=top;
        Item item=top.item;
        top=top.next;
        N--;
        oldTop=null;//Let GC to do
        return item;
    }
    
    public String toString(){
        String s="";
        Node temp=top;
        while(temp!=null){
            s+=temp.item+" ";
            temp=temp.next;
            }
        return s;
    }
    
//Iterator  
    @Override
    public Iterator<Item> iterator() {
        return new helpIterator();
    }
    
    public class helpIterator implements Iterator<Item>{
        private Node curr=top;
        public boolean hasNext(){return curr!=null;}
        public Item next(){
            Item item=curr.item;
            curr=curr.next;
            return item;
        }
    }
    
    /**
     * Test unit
     * @param args
     */
    public static void main(String[] args) {
        Stack<Integer> test=new Stack<>();
        for(int i=0;i<10;i++){
            test.push(i);
        }
        System.out.println(test);

        while(!test.isEmpty())
            test.pop();
        System.out.println(test);
    }
    
}

As you can see, the structure set the top node as the top of stack. If push, we set the new node of the top, and make its next is oldTop. If pop, we just make top equal to top.next, and set the oldTop as null and make the GC to deal with it.

Sixth, let's see the queue based on Linked-list.


import java.util.Iterator;

public class Queue<Item> implements Iterable<Item>{
    private class Node{
        Item item;
        Node next;
    }
    
    private Node first;//The head of the queue
    private Node last; //The tail of the queue
    private int N;     //The number of the item of the queue

    public boolean isEmpty(){return N==0;}//or first==null
    public int size(){return N;}
    
    public void enqueue(Item item){
        //Add the item to the tail of the list
        Node oldLast=last;
        last = new Node();
        last.item=item;
        last.next=null;
        if(first==null) first=last;
        else oldLast.next=last;
        N++;
    } 
    
    public Item dequeue(){
        //Remove the item form the head of the list
        Item item=first.item;
        first=first.next;
        if(isEmpty()) last=null;
        N--;
        return item;
    }
    
    public String toString(){
        String s="";
        Node temp=first;
        while(temp!=null){
            s+=temp.item+" ";
            temp=temp.next;
        }
        return s;
    }
        
//Iterator  
    @Override
    public Iterator<Item> iterator() {
        return new helpIterator();
    }
    private class helpIterator implements Iterator<Item>{
        Node curr=first;
        public boolean hasNext(){
            return curr!=null;
        }
        public Item next(){
            Item item=curr.item;
            curr=curr.next;
            return item;
        }
        public void remove(){
            
        }
    }
    
    /**
     * Test unit
     * @param args
     */
    public static void main(String[] args) {
        Queue<Integer> test = new Queue<>();
        for(int i=0;i<10;i++)
        test.enqueue(i);
        System.out.println(test);
        test.dequeue();
        System.out.println(test);
        for(Integer e:test){
            System.out.println(e);
        }
    }
}

As the other article I wrote, of the operation of Linked-list, we must care about whether it is null. The stack we don't need care for the problem, but in queue, we must. Because we need to maintain two pointers, one is head, other is tail. The detail you can read the enqueue and dequeue.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,240评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,328评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,182评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,121评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,135评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,093评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,013评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,854评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,295评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,513评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,678评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,398评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,989评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,636评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,801评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,657评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,558评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,322评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,031评论 3 20
  • 十二月的尾巴 被涂成了明亮的颜色 明天就要十九岁的我 偷偷藏起了巧克力 还有草莓味的千层糕 脱下了灰色的运动装 穿...
    喜栗阅读 576评论 4 8
  • 收获:《善用时间》这本书是行动指南,叶老师的建议是两遍,一遍通读,一遍根据自己出现的问题,找到相应的章节进行反复阅...
    Sophia3487阅读 261评论 0 3
  • 右手高举手机,左手岔开剪刀额头微垂下巴微收脸儿微侧嘴角微翘媚眼微台胸部微挺小腹微吸咔嚓——满意被定格了 缝缝补补发...
    俗然阅读 488评论 0 3