Problem
Implement a stack. You can use any data structure inside a stack except stack itself to implement it.
Examplepush(1)
pop()
push(2)
top() // return 2
pop()
isEmpty() // return true
push(3)
isEmpty() // return false
class ListNode { int val; ListNode next; public ListNode(int val) { this.val = val; } } public class Stack { ListNode head; public Stack() { head = new ListNode(0); head.next = null; } public void push(int x) { ListNode node = new ListNode(x); node.next = head.next; head.next = node; } /* * @return: nothing */ public void pop() { if (head.next != null) { head.next = head.next.next; } } /* * @return: An integer */ public int top() { return head.next.val; } /* * @return: True if the stack is empty */ public boolean isEmpty() { return head.next == null; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/68073.html
摘要: Problem Implement a function to check if a linked list is a palindrome. Example Given 1->2->1, return true. Key create new list nodes: ListNode pre = null; //null, 1-2-3-4 //1-null, 2-3-4 //2-1...
Problem Flatten a binary tree to a fake linked list in pre-order traversal.Here we use the right pointer in TreeNode as the next pointer in ListNode. Example 1 1 ...
摘要:剑指用两个栈模拟队列声明文章均为本人技术笔记,转载请注明出处解题思路实现功能用两个栈模拟实现一个队列的,和操作解题思路假设有两个栈队列实现始终用入栈实现队列和实现由于依次出栈并压入中,恰好保证中顺序与模拟队列顺序一致,始终保证栈顶元素为模拟 剑指offer/LintCode40_用两个栈模拟队列 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault.com...
Problem Implement a stack with min() function, which will return the smallest number in the stack. It should support push, pop and min operation all in O(1) cost. Example push(1)pop() // return 1pus...
摘要:首先,根据迭代器需要不断返回下一个元素,确定用堆栈来做。堆栈初始化数据结构,要先从后向前向堆栈压入中的元素。在调用之前,先要用判断下一个是还是,并进行的操作对要展开并顺序压入对直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...
阅读 2828·2021-09-10 10:51
阅读 2196·2021-09-02 15:21
阅读 3184·2019-08-30 15:44
阅读 834·2019-08-29 18:34
阅读 1636·2019-08-29 13:15
阅读 3284·2019-08-26 11:37
阅读 2683·2019-08-26 10:46
阅读 1084·2019-08-26 10:26