Skip to content

Instantly share code, notes, and snippets.

# 3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array).The stack supports the following operations: push, pop, peek, and isEmpty.
from stack import Stack
def sort(stack):
result = Stack()
while stack.isEmpty() is not True:
tmp = stack.pop()
while result.isEmpty() is not True and result.peek() > tmp:
@yokiy
yokiy / MyQueue.py
Last active August 29, 2015 14:03
cc 3.5
# cc 3.5 Implement a MyQUeue class which implements a queue using two stacks
from stack import Stack
class MyQueue:
def __init__(self):
self.inque = Stack()
self.outque = Stack()
@yokiy
yokiy / tower.py
Created July 5, 2014 18:03
cc 3.4
# cc 3.4 Tower of Hanoi
from stack import Stack, Node
class tower:
def __init__(self):
self.start = Stack()
self.dest = Stack()
self.buff = Stack()
@yokiy
yokiy / SetOfStacks.py
Last active August 29, 2015 14:03
cc 3.3
# 3.3 set of stacks
from stack import Stack, Node
class SetOfStacks:
def __init__(self, limit):
self.last = Stack()
self.limit = limit
self.stacklist = [self.last]
#3.2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
from stack import Stack, Node
class stackmin(Stack):
def __init__(self):
Stack.__init__(self)
self.min = Stack()
self.minItem = None
@yokiy
yokiy / stack.py
Last active August 29, 2015 14:03
cc 3.1
#stack structure in python
class Node:
def __init__(self,item):
self.item = item
self.next = None
class Stack:
@yokiy
yokiy / findloop.py
Created June 29, 2014 00:00
cc 2.6
# 2.6 Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop.
#slower and faster pointers
from LinkedList import Node, LinkedList
def findloop(ls):
p1 = ls.head
p2 = ls.head
if p2 is None or p2.next is None:
return null
#cc 2.5 addition with reverse digit
from LinkedList import Node, LinkedList
def addReverse(ls1, ls2):
add1 = ls1.head
add2 = ls2.head
#2.4 prtition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.
#creat two list, <x & >= x, merge them at last
from LinkedList import LinkedList, Node
def partition(self, x):
if self is None:
return
small = LinkedList()
#2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
from LinkedList import LinkedList, Node
def deleteNode(node):
if node is None or node.next is None:
return False
node.data = node.next.data
node.next = node.next.next
return True