【每日一题】2022年1月25日-赋乐科技-用链表实现一个栈,类似-链表实现一个队列
package com.jhliu20.real; import java.util.LinkedList; public class MyStack { private LinkedList linkedList; public MyStack() { linkedList = new LinkedList(); } public void push(Object object) { linkedList.addFirst(object); } public Object pop() { return linkedList.removeFirst(); } public Object peek() { return linkedList.getFirst(); } public boolean isEmpty() { return linkedList.isEmpty(); } }
我是智障!
list就是链表,有现成的链表
为何要自己去实现???????????
package com.jhliu20.real; public class StackTest { interface ListNode { ListNode listNode; int val; ListNode next; public ListNode(int val) { listNode.val = val; listNode.next = null; } } class Stack { ListNode cur; ListNode head; public Stack() { head = new ListNode(0); head.next = null; } public Stack(int val) { cur = new ListNode(val); } /** * 头插法入栈 * @param val */ public void push(int val) { head.next = new Stack(val); } public int pop() { //移除最后一个节点 ListNode p = head; ListNode dummy = head; while(p != cur) { dummy = p; p = p.next; } cur = dummy; return p.val; } public int peek() { return cur.val; } public boolean isEmpty() { return head.next == null ? true : false; } } }
如何自己定义一个链表类!!!!!!但是,有现成的啊,LinkedList就是链表【单列集合中的LinkedList就是一个链表】
class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15844666.html