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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/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 ...
摘要:劍指用兩個棧模擬隊列聲明文章均為本人技術(shù)筆記,轉(zhuǎn)載請注明出處解題思路實現(xiàn)功能用兩個棧模擬實現(xiàn)一個隊列的,和操作解題思路假設(shè)有兩個棧隊列實現(xiàn)始終用入棧實現(xiàn)隊列和實現(xiàn)由于依次出棧并壓入中,恰好保證中順序與模擬隊列順序一致,始終保證棧頂元素為模擬 劍指offer/LintCode40_用兩個棧模擬隊列 聲明 文章均為本人技術(shù)筆記,轉(zhuǎn)載請注明出處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...
摘要:首先,根據(jù)迭代器需要不斷返回下一個元素,確定用堆棧來做。堆棧初始化數(shù)據(jù)結(jié)構(gòu),要先從后向前向堆棧壓入中的元素。在調(diào)用之前,先要用判斷下一個是還是,并進行的操作對要展開并順序壓入對直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...
閱讀 2847·2021-09-10 10:51
閱讀 2214·2021-09-02 15:21
閱讀 3205·2019-08-30 15:44
閱讀 868·2019-08-29 18:34
閱讀 1651·2019-08-29 13:15
閱讀 3321·2019-08-26 11:37
閱讀 2696·2019-08-26 10:46
閱讀 1106·2019-08-26 10:26