棧和隊列相關(guān)數(shù)據(jù)結(jié)構(gòu)的設(shè)計問題

題目一:設(shè)計一個帶有g(shù)etMin功能的棧

[leetcode155]https://leetcode.com/problems/min-stack/

解法一:兩個棧冒晰,其中help棧壓入的都是最小值,同步壓入抬闷,同步彈出,最省時間

public class MinStack {
    Stack<Integer> data;
    Stack<Integer> help;
    /** initialize your data structure here. */
    public MinStack() {
        data=new Stack<Integer>();
        help=new Stack<Integer>();
    }
    
    public void push(int x) {
        if(data.isEmpty()){
            data.push(x);
            help.push(x);
        }else{
            data.push(x);
            help.push(Math.min(help.peek(),x));
        }    
    }
    
    public void pop() {
        if(data.isEmpty())
            throw new RuntimeException("your stack is rmpty");
        data.pop();
        help.pop();
    }
    
    public int top() {
        if(data.isEmpty())
            throw new RuntimeException("your stack is rmpty");
        return data.peek();
    }
    
    public int getMin() {
        return help.peek();
    }
}

解法二:兩個棧,壓入時當(dāng)前數(shù)小于等于棧頂元素才壓入耕突,彈出時當(dāng)前棧頂大于help棧頂才彈出笤成,省了一些空間

public class MinStack {
    Stack<Integer> data;
    Stack<Integer> help;
    /** initialize your data structure here. */
    public MinStack() {
        data=new Stack<Integer>();
        help=new Stack<Integer>();
    }
    
    public void push(int x) {
        if(data.isEmpty()){
            data.push(x);
            help.push(x);
        }else{
            data.push(x);
            if(x<=help.peek())
                help.push(x);
        }    
    }
    
    public void pop() {
        // if(data.isEmpty())
        //     throw new RuntimeException("your stack is rmpty");
        int cur=data.peek();
        data.pop();
        if(cur==help.peek())
            help.pop();
    }
    
    public int top() {
        // if(data.isEmpty())
        //     throw new RuntimeException("your stack is rmpty");
        return data.peek();
        
    }
    
    public int getMin() {
        return help.peek();
    }
}

方法三:只使用一個棧,另外使用一個變量來記錄最小眷茁,棧中壓入的是與最小值的差炕泳。

public class MinStack {
    private long min;
    Stack<Long> stack;

    /** initialize your data structure here. */
    public MinStack() {
        stack=new Stack<Long>();
    }
    
    public void push(int x) {
        if(stack.isEmpty()){
            min=x;
            stack.push(0L);//為了和后面統(tǒng)一起來
        }
        else{
            stack.push(x-min);
            if(x<min)
                min=x;
        }
    }
    
    public void pop() {
        if(stack.isEmpty())
            return;
        long pop=stack.pop();
        if(pop<0)
            min=min-pop;
    }
    
    public int top() {
        long peek=stack.peek();
        if(peek>0)
            return (int)(min+peek);
        else
            return (int)min;
        
    }
    
    public int getMin() {
        return (int)min;
    }
}

題目二 兩個棧實現(xiàn)隊列

兩個棧data help,只要注意兩點
1. help為空的時候才能往里面導(dǎo)數(shù)上祈。

  1. 導(dǎo)數(shù)就要把data中的所有數(shù)都導(dǎo)完培遵。
class MyQueue {
   Stack<Integer> data=new Stack<Integer>();
   Stack<Integer> help=new Stack<Integer>();
   // Push element x to the back of queue.
   public void push(int x) {
       data.push(x);
   }

   // Removes the element from in front of queue.
   public void pop() {
       if(help.isEmpty()&&data.isEmpty())
           throw new RuntimeException("your queue is empty");
       else if(help.isEmpty()){
           while(!data.isEmpty())
               help.push(data.pop());
       }
       help.pop();
   }

   // Get the front element.
   public int peek() {
       if(help.isEmpty()&&data.isEmpty())
           throw new RuntimeException("your stack is empty");
       else if(help.isEmpty()){
           while(!data.isEmpty())
               help.push(data.pop());
       }
       return help.peek();
   }

   // Return whether the queue is empty.
   public boolean empty() {
       return help.isEmpty()&&data.isEmpty();
   }
}

題目三 兩個隊列實現(xiàn)棧

class MyStack {
   Queue<Integer> data=new LinkedList<Integer>();
   Queue<Integer> help=new LinkedList<Integer>();
   // Push element x onto stack.
   public void push(int x) {
       data.add(x);
   }

   // Removes the element on top of the stack.
   public void pop() {
       if(data.isEmpty())
           throw new RuntimeException("your stack is empty!");
       while(data.size()!=1){
           help.add(data.poll());
       }
       data.poll();
       while(!help.isEmpty()){
           data.add(help.poll());
       }
   }

   // Get the top element.
   public int top() {
       if(data.isEmpty())
           throw new RuntimeException("your stack is empty!");
       while(data.size()!=1){
           help.add(data.poll());
       }
       int tmp=data.peek();
       help.add(data.poll());//小心這里
       while(!help.isEmpty()){
           data.add(help.poll());
       }
       return tmp;
   }

   // Return whether the stack is empty.
   public boolean empty() {
       return data.isEmpty();
   }
}

題目四 僅使用遞歸實現(xiàn)棧的逆序

有利于對于遞歸的理解
要求只使用遞歸實現(xiàn)一個棧的逆序

思路:

假如不限條件浙芙,要實現(xiàn)一個棧的逆序,那么我們直接借助一個棧就可以實現(xiàn)了荤懂,這里不能再顯試的使用棧茁裙,那么我們就使用遞歸來利用系統(tǒng)的遞歸棧來實現(xiàn)。
這里首先思考getAndRemoveLast這個遞歸函數(shù)节仿,用于得到一個棧的棧底元素晤锥,并且刪除設(shè)個棧底元素。然后現(xiàn)在我們在每次遞歸返回的時候把之前保留的元素加到棧中廊宪,就可以實現(xiàn)逆序矾瘾。

public static void reverse(Stack<Integer> stack){
    if(stack.isEmpty())
        return;
    int i=getAndRemoveLast(stack);
    reverse(stack);
    stack.push(i);
}
public static int getAndRemoveLast(Stack<Integer> stack){
    int res=stack.pop();
    if(stack.isEmpty()){
        return res;
    }
    else{
        int last=getAndRemoveLast(stack);
        stack.push(res);
    
        return last;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市箭启,隨后出現(xiàn)的幾起案子壕翩,更是在濱河造成了極大的恐慌,老刑警劉巖傅寡,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件放妈,死亡現(xiàn)場離奇詭異,居然都是意外死亡荐操,警方通過查閱死者的電腦和手機芜抒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來托启,“玉大人宅倒,你說我怎么就攤上這事⊥退剩” “怎么了拐迁?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疗绣。 經(jīng)常有香客問我线召,道長,這世上最難降的妖魔是什么多矮? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任灶搜,我火速辦了婚禮,結(jié)果婚禮上工窍,老公的妹妹穿的比我還像新娘割卖。我一直安慰自己,他們只是感情好患雏,可當(dāng)我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布鹏溯。 她就那樣靜靜地躺著,像睡著了一般淹仑。 火紅的嫁衣襯著肌膚如雪丙挽。 梳的紋絲不亂的頭發(fā)上肺孵,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天,我揣著相機與錄音颜阐,去河邊找鬼平窘。 笑死,一個胖子當(dāng)著我的面吹牛凳怨,可吹牛的內(nèi)容都是我干的瑰艘。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼肤舞,長吁一口氣:“原來是場噩夢啊……” “哼紫新!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起李剖,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤芒率,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后篙顺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體偶芍,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年德玫,在試婚紗的時候發(fā)現(xiàn)自己被綠了腋寨。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡化焕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出铃剔,到底是詐尸還是另有隱情撒桨,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布键兜,位于F島的核電站凤类,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏普气。R本人自食惡果不足惜谜疤,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望现诀。 院中可真熱鬧夷磕,春花似錦、人聲如沸仔沿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽封锉。三九已至绵跷,卻和暖如春膘螟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碾局。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工荆残, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人净当。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓内斯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蚯瞧。 傳聞我的和親對象是個殘疾皇子嘿期,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,055評論 2 355

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

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,747評論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理埋合,服務(wù)發(fā)現(xiàn)备徐,斷路器,智...
    卡卡羅2017閱讀 134,665評論 18 139
  • 課程介紹 先修課:概率統(tǒng)計甚颂,程序設(shè)計實習(xí)蜜猾,集合論與圖論 后續(xù)課:算法分析與設(shè)計,編譯原理振诬,操作系統(tǒng)蹭睡,數(shù)據(jù)庫概論,人...
    ShellyWhen閱讀 2,290評論 0 3
  • 1.把二元查找樹轉(zhuǎn)變成排序的雙向鏈表 題目: 輸入一棵二元查找樹赶么,將該二元查找樹轉(zhuǎn)換成一個排序的雙向鏈表肩豁。 要求不...
    曲終人散Li閱讀 3,319評論 0 19
  • 很討厭有一種人 滿嘴雞湯寫著些文縐縐的大道理 然后把自己經(jīng)歷過的所謂的世態(tài)炎涼說得多么天花龍鳳 事實上現(xiàn)實卻是做事...
    Aomyl閱讀 273評論 0 0