算法练习(52): 双向队列与栈(1.3.48-1.3.50)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法(第4版)

知识点

  • 队列、栈或 steque

题目

1.3.48 双向队列与栈。用一个双向队列实现两个栈,保证每个栈操作只需要常数次的双向队列操作。(请见练习 1.3.33)


1.3.48 Two stacks with a deque. Implement two stacks with a single deque so that each operation takes a constant number of deque operations (see Exercise 1.3.33).

分析

要实现一个栈,即是实现栈的 push,pop 等操作。

public class  Stack<Item> {
    private int N = 0;
    private Node topNode = null;
    private class Node {
        Item item;
        Node next;
    }

    private Deque<Item> deque;


    public void push(Item item) {
        if (deque == null) {
            deque = new Deque<Item>();
        }
        deque.pushRight(item);
    }

    public Item pop() {
        return deque.popRight();
    }

    public boolean isEmpty() {
        return deque.isEmpty();
    }

    public int size() {
        return deque.size();
    }
}

测试用例

 public static void main(String[] args) {
    Stack<String> stack = new Stack();
    stack.push("I");
    stack.push("am");
    stack.push("Kyson");
    stack.push("You");
    stack.push("are");

    System.out.println(stack.pop());
    System.out.println("size:" + stack.size());

    System.out.println(stack.pop());
    System.out.println("size:" + stack.size());

    System.out.println(stack.pop());
    System.out.println("size:" + stack.size());


    System.out.println(stack.pop());
    System.out.println("size:" + stack.size());

    System.out.println(stack.pop());
    System.out.println("size:" + stack.size());
}

题目

1.3.49 栈与队列。用三个栈实现一个队列,保证每个队列操作(在最坏情况下)都只需要常数次的栈操作。


1.3.49 Queue with three stacks. Implement a queue with three stacks so that each queue operation takes a constant (worst-case) number of stack operations. Warning : high degree of difficulty.

分析

queue.new() : Stack1 = Stack.new(<Stack>);  
              Stack2 = Stack1;  

enqueue(element): Stack3 = Stack.new(<TypeOf(element)>); 
                  Stack3.push(element); 
                  Stack2.push(Stack3);
                  Stack3 = Stack.new(<Stack>);
                  Stack2.push(Stack3);
                  Stack2 = Stack3;                       

dequeue(): Stack3 = Stack1.pop(); 
           Stack1 = Stack1.pop();
           dequeue() = Stack1.pop()
           Stack1 = Stack3;

isEmtpy(): Stack1.isEmpty();

演示如下:

 | | | |3| | | |
 | | | |_| | | |
 | | |_____| | |
 | |         | |
 | |   |2|   | |
 | |   |_|   | |
 | |_________| |
 |             |
 |     |1|     |
 |     |_|     |
 |_____________|

题目

1.3.50 快速出错的迭代器。修改 Stack 的迭代器代码,确保一旦用例在迭代器中(通过 push() 或 pop() 操作)修改集合数据就抛出一个 java.util.ConcurrentModificationException 异常。


1.3.50 Fail-fast iterator. Modify the iterator code in Stack to immediately throw a java.util.ConcurrentModificationException if the client modifies the collection (via push() or pop()) during iteration? b).
Solution: Maintain a counter that counts the number of push() and pop() operations. When creating an iterator, store this value as an Iterator instance variable. Before each call to hasNext() and next(), check that this value has not changed since con- struction of the iterator; if it has, throw the exception.

答案

public class Stack<Item> implements Iterable<Item>
{
    private int N;
    private Node first;
    private int pushPopCount;
    
    private class Node {
        Item item;
        Node next;
    }
    
    public Stack() {
    }
    
    public Stack(Stack s)
    {
        Node right=new Node();
        Node oldright;
        for(Object i:s) {
            oldright=right;
            right=new Node();
            right.item=(Item) i;
            right.next=null;
            if(isEmpty()) {
                first=right;
            } else {
                oldright.next=right;
            }
            N++;
        }
    }
    
    public boolean isEmpty() {
        return N==0;
    }
    
    public int size() {
        return N;
    }
    
    public void push(Item item) {
        Node oldfirst=first;
        first=new Node();
        first.item=item;
        first.next=oldfirst;
        N++;
        pushPopCount++;
    }
    
    public Item pop() {
        Item item=first.item;
        first=first.next;
        N--;
        pushPopCount++;
        return item;
    }
    
    
    public Item peek() {
        Item item=first.item;
        return item;
    }
    
    public void catenation(Stack s) {
        while(!s.isEmpty()) {
            this.push((Item)s.pop());
        }
    }
    
    public Iterator<Item> iterator() {
        return new ListIterator();
    }
    
    private class ListIterator implements Iterator<Item> {
        private Node current=first;
        private int originatedPushPopCount;
        public ListIterator() {
            originatedPushPopCount=pushPopCount;
        }
        public boolean hasNext() {
            return current!=null;
        }
        public void remove(){}
        public Item next()
        {
            if(originatedPushPopCount!=pushPopCount)
                throw new java.util.ConcurrentModificationException();
            Item item=current.item;
            current=current.next;
            return item;
        }
    }
}

参考

How to implement a queue with three stacks?

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,660评论 0 33
  • 新絮飞,荻花殇,满地凄凉。残酒回肠,一段情,两断伤。怎叫梨花雨凉? 茫茫清溪霜含月,孤帆夜影,残雁点点...
    石石头阅读 297评论 0 2
  • 第一次听说大冰,是最恋军时节,当时以为是一个很厉害的兵哥哥。待到朋友解释此“冰”非彼“兵”时,一脸的不屑,暗叹此人...
    剑羽风凌阅读 950评论 0 1
  • 北上广的你痛并快乐着 2017-10-20 小曜 沸腾的城与孤独的人 作者 小曜 熙熙攘攘的地铁...
    田野同学阅读 208评论 0 2
  • 作为88届奥斯卡最佳动画长片,较之《疯狂动物城》在中国市场的红红火火、老少通吃,《头脑特工队》在中国电影市场并没有...
    卡萨布兰卡遥望佛罗伦萨阅读 385评论 0 1