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