Implement a stack. You can use any data structure inside a stack except stack itself to implement it.

Have you met this question in a real interview?

 
 
Example

push(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false

解法一:

 class Stack {
public:
struct Node {
int val;
Node *prev, *next;
Node(int v) {
val = v;
prev = NULL;
next = NULL;
}
}; Node *dummy;
Node *tail;
Stack() {
dummy = new Node();
tail = dummy;
} ~Stack() { } void push(int x) {
tail->next = new Node(x);
tail->next->prev = tail;
tail = tail->next;
} // Pop the top of the stack
void pop() {
if (dummy->next == NULL) {
return;
}
Node *prev = tail->prev;
prev->next = NULL;
tail = prev;
} // Return the top of the stack
int top() {
if (dummy->next == NULL) {
return -;
}
return tail->val;
} // Check the stack is empty or not.
bool isEmpty() {
if (dummy->next == NULL) {
return true;
}
return false;
}
};

用链表实现栈,因为栈pop出的是最后一个,如果用尾插法的单向链表明显不太方便,所以用双向链表。

参考@YI 的代码

https://yixuanwangblog.wordpress.com/2016/09/04/lintcode-495-implement-stack/

解法二:

 class ListNode{
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}; public class Stack {
ListNode head;
public Stack(){
head = new ListNode(0);
} /*
* @param x: An integer
* @return: nothing
*/
public void push(int x) {
ListNode node = new ListNode(x);
node.next = head.next;
head.next = node;
} /*
* @return: nothing
*/
public int pop() {
ListNode top = head.next;
head.next = head.next.next;
return top.val;
} /*
* @return: An integer
*/
public int top() {
return head.next.val;
} /*
* @return: True if the stack is empty
*/
public boolean isEmpty() {
if (head.next == null) {
return true;
} else{
return false;
}
}
}

用链表实现栈,使用头插法。

参考@zhengyang2015 的代码

https://zhengyang2015.gitbooks.io/lintcode/implement_stack_495.html

最新文章

  1. 向上弹出菜单jQuery插件
  2. git之常用指令
  3. linux shell工具集合
  4. ECS 安装redis 及安装PHPredis的扩展
  5. Andaroid L新特性
  6. MM32 RTC学习(兼容STM32)
  7. 使用 Cordova+Visual Studio 创建跨平台移动应用(2)
  8. 一起来学jquery!
  9. mockplus 原型设计工具
  10. 中国科学技术大学统一身份认证系统CAS
  11. 使用普通用户执行 docker
  12. python之约束, 异常处理, md5
  13. Oracle简单语句查询
  14. VB.NET文件读写(C#可以改写)
  15. 谷歌算法研究员:我为什么钟爱PyTorch?
  16. 界面编程之QT的Socket通信20180730
  17. Word揭秘:公式还能这么玩!
  18. Django内置的分页模块
  19. HP-UNIX平台修改Oracle processes参数报错:ORA-27154、ORA-27300、ORA-27301、ORA-27302
  20. go系列(5)- beego自己写controller

热门文章

  1. C++ Java C#泛型
  2. mac 下安装 plink
  3. [Android Pro] android中permission_group与permisson区别、作用
  4. HTML5基础知识汇总_(2)自己定义属性及表单新特性
  5. 15个CSS3和jQuery的超棒页面过渡效果教程
  6. OpenCV和Matlab
  7. XP如何找到网上邻居
  8. Js、JQuery脚本兼容
  9. 有些类库(node.js版)
  10. 《Java程序猿面试笔试宝典》之 什么是AOP