用链表实现栈,详细代码如下:
package stack;
public class StackByLinkedlist {
ListNode popNode;
public boolean push(String item) {
ListNode temp = popNode;
popNode = new ListNode(item);
popNode.next = temp;
return true;
}
public String pop() {
if (popNode == null) {
return null;
}
String result = popNode.val;
popNode = popNode.next;
return result;
}
public String peek() {
if (popNode == null) {
return null;
}
String result = popNode.val;
return result;
}
public boolean empty() {
return popNode == null;
}
class ListNode {
String val;
ListNode next;
ListNode(String x) {
val = x;
}
}
}
复杂度分析
时间复杂度 : push 和 pop 均为:O(1)
空间复杂度 : push 和 pop 均为:O(1)
网友评论