|
|
@ -1,7 +1,7 @@
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
File: linkedlist_stack.py
|
|
|
|
File: linkedlist_stack.py
|
|
|
|
Created Time: 2022-11-25
|
|
|
|
Created Time: 2022-11-29
|
|
|
|
Author: Krahets (krahets@163.com)
|
|
|
|
Author: Peng Chen (pengchzn@gmail.com)
|
|
|
|
'''
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
|
import os.path as osp
|
|
|
|
import os.path as osp
|
|
|
@ -11,14 +11,11 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
|
|
|
from include import *
|
|
|
|
from include import *
|
|
|
|
|
|
|
|
|
|
|
|
""" 基于链表实现的栈 """
|
|
|
|
""" 基于链表实现的栈 """
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LinkedListStack:
|
|
|
|
class LinkedListStack:
|
|
|
|
def __init__(self):
|
|
|
|
def __init__(self):
|
|
|
|
self.head = None
|
|
|
|
self.head = None
|
|
|
|
|
|
|
|
|
|
|
|
""" 获取栈的长度 """
|
|
|
|
""" 获取栈的长度 """
|
|
|
|
|
|
|
|
|
|
|
|
def size(self):
|
|
|
|
def size(self):
|
|
|
|
cnt = 0
|
|
|
|
cnt = 0
|
|
|
|
temp = self.head
|
|
|
|
temp = self.head
|
|
|
@ -28,28 +25,24 @@ class LinkedListStack:
|
|
|
|
return cnt
|
|
|
|
return cnt
|
|
|
|
|
|
|
|
|
|
|
|
""" 判断栈是否为空 """
|
|
|
|
""" 判断栈是否为空 """
|
|
|
|
|
|
|
|
|
|
|
|
def is_empty(self):
|
|
|
|
def is_empty(self):
|
|
|
|
if not self.head.val and not self.head.next:
|
|
|
|
if not self.head.val and not self.head.next:
|
|
|
|
return True
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
""" 入栈 """
|
|
|
|
""" 入栈 """
|
|
|
|
|
|
|
|
|
|
|
|
def push(self, val):
|
|
|
|
def push(self, val):
|
|
|
|
temp = ListNode(val)
|
|
|
|
temp = ListNode(val)
|
|
|
|
temp.next = self.head
|
|
|
|
temp.next = self.head
|
|
|
|
self.head = temp
|
|
|
|
self.head = temp
|
|
|
|
|
|
|
|
|
|
|
|
""" 出栈 """
|
|
|
|
""" 出栈 """
|
|
|
|
|
|
|
|
|
|
|
|
def pop(self):
|
|
|
|
def pop(self):
|
|
|
|
pop = self.head.val
|
|
|
|
pop = self.head.val
|
|
|
|
self.head = self.head.next
|
|
|
|
self.head = self.head.next
|
|
|
|
return pop
|
|
|
|
return pop
|
|
|
|
|
|
|
|
|
|
|
|
""" 访问栈顶元素 """
|
|
|
|
""" 访问栈顶元素 """
|
|
|
|
|
|
|
|
|
|
|
|
def peek(self):
|
|
|
|
def peek(self):
|
|
|
|
return self.head.val
|
|
|
|
return self.head.val
|
|
|
|
|
|
|
|
|
|
|
|