资讯专栏INFORMATION COLUMN

[LintCode] Implement Stack (using ListNode)

chenjiang3 / 1653人阅读

Problem

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

Example

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

Solution
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

相关文章

  • [LintCode] Palindrome Linked List

    摘要: 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...

    Tamic 评论0 收藏0
  • [LintCode/LeetCode] Flatten Binary Tree to Linked

    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 ...

    TNFE 评论0 收藏0
  • 剑指offer/LintCode40_用两个栈模拟队列

    摘要:剑指用两个栈模拟队列声明文章均为本人技术笔记,转载请注明出处解题思路实现功能用两个栈模拟实现一个队列的,和操作解题思路假设有两个栈队列实现始终用入栈实现队列和实现由于依次出栈并压入中,恰好保证中顺序与模拟队列顺序一致,始终保证栈顶元素为模拟 剑指offer/LintCode40_用两个栈模拟队列 声明 文章均为本人技术笔记,转载请注明出处https://segmentfault.com...

    bawn 评论0 收藏0
  • [LintCode/LeetCode] Min Stack/Max Stack

    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...

    GHOST_349178 评论0 收藏0
  • [LintCode/LeetCode] Flatten Nested List Iterator

    摘要:首先,根据迭代器需要不断返回下一个元素,确定用堆栈来做。堆栈初始化数据结构,要先从后向前向堆栈压入中的元素。在调用之前,先要用判断下一个是还是,并进行的操作对要展开并顺序压入对直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...

    spacewander 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<