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.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子锤岸,更是在濱河造成了極大的恐慌,老刑警劉巖蜡饵,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)整袁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來佑吝,“玉大人坐昙,你說我怎么就攤上這事〖8颍” “怎么了民珍?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵襟士,是天一觀的道長盗飒。 經(jīng)常有香客問我,道長陋桂,這世上最難降的妖魔是什么逆趣? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮嗜历,結(jié)果婚禮上宣渗,老公的妹妹穿的比我還像新娘抖所。我一直安慰自己,他們只是感情好痕囱,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布田轧。 她就那樣靜靜地躺著,像睡著了一般鞍恢。 火紅的嫁衣襯著肌膚如雪傻粘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天帮掉,我揣著相機(jī)與錄音弦悉,去河邊找鬼。 笑死蟆炊,一個胖子當(dāng)著我的面吹牛稽莉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播涩搓,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼污秆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了昧甘?” 一聲冷哼從身側(cè)響起混狠,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疾层,沒想到半個月后将饺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡痛黎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年予弧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片湖饱。...
    茶點(diǎn)故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡掖蛤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出井厌,到底是詐尸還是另有隱情蚓庭,我是刑警寧澤,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布仅仆,位于F島的核電站器赞,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏墓拜。R本人自食惡果不足惜港柜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧夏醉,春花似錦爽锥、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至靶擦,卻和暖如春肠槽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背奢啥。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工秸仙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人桩盲。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓寂纪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親赌结。 傳聞我的和親對象是個殘疾皇子捞蛋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,312評論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網(wǎng)事_79a3閱讀 11,961評論 3 20
  • 十二月的尾巴 被涂成了明亮的顏色 明天就要十九歲的我 偷偷藏起了巧克力 還有草莓味的千層糕 脫下了灰色的運(yùn)動裝 穿...
    喜栗閱讀 573評論 4 8
  • 收獲:《善用時間》這本書是行動指南,葉老師的建議是兩遍柬姚,一遍通讀拟杉,一遍根據(jù)自己出現(xiàn)的問題,找到相應(yīng)的章節(jié)進(jìn)行反復(fù)閱...
    Sophia3487閱讀 260評論 0 3
  • 右手高舉手機(jī)量承,左手岔開剪刀額頭微垂下巴微收臉兒微側(cè)嘴角微翹媚眼微臺胸部微挺小腹微吸咔嚓——滿意被定格了 縫縫補(bǔ)補(bǔ)發(fā)...
    俗然閱讀 485評論 0 3