def sort_stack(s): sort = Stack() while not s.is_empty(): top_node = s.pop() if sort.is_empty() or sort.peek().val >= top_node.val: sort.push(top_node.val) else: while (not sort.is_empty()) and sort.peek().val < top_node.val: n = sort.pop() s.push(n.val) sort.push(top_node.val) s.head = sort.head s.tail = sort.tail
def by_stack(self, header): """ 首先肯定要遍历链表,此时我们肯定要遍历链表,但是输出确实逆序的,因而我们可利用栈来实现这一功能。 """ s = Stack() while header is not None: s.push(header.val) header = header.next while not s.is_empty(): print(s.pop())