public static Stack reverse(Stack input) { Stack reversed = new Stack(); int? runner = input.pop(); while (runner != null) { reversed.push((int)runner); runner = input.pop(); } return reversed; }
public static Stack reverse_if_backwards(Stack input) { Stack copy = (Stack)input.Clone(); int? first; int? last; int? runner; Stack temp = new Stack(); runner = input.pop(); last = runner; while (runner != null) { if (runner != null) { temp.push((int)runner); } runner = input.pop(); } first = temp.peek(); //Console.WriteLine("First: " + first + " - Last: " + last); if (first > last) { // smallest on top return temp; } else { // largest on top return copy; } }
public static void printStack(Stack t) { Stack copy = (Stack)t.Clone(); int levels = 0; int? item = copy.pop(); Console.WriteLine("---"); while (item != null) { levels++; Console.WriteLine("Stack level " + levels + ": " + item); item = copy.pop(); } Console.WriteLine("---"); Console.WriteLine("\n"); }
public void push(int d) { Stack below = new Stack(); Stack above = new Stack(); if (container == null) { container = new Stack(); container.push(d); return; } Stack reversed = new Stack(); Stack temp = new Stack(); reversed = reverse(container); int? runner = reversed.pop(); while (runner != null) { if (runner >= d) { above.push((int)runner); } else { below.push((int)runner); } runner = reversed.pop(); } below = reverse_if_backwards(below); below.push(d); //Console.WriteLine("below: "); //Program.printStack(below); int? first; int? last; runner = below.pop(); last = runner; while (runner != null) { temp.push((int)runner); runner = below.pop(); } //Console.WriteLine("above: "); //Program.printStack(above); runner = above.pop(); last = runner; while (runner != null) { temp.push((int)runner); runner = above.pop(); } first = temp.peek(); //Console.WriteLine("First: " + first + " - Last: " + last); //if (first > last) //{ // Console.WriteLine("Reversed: " + first + " - " + last); // temp = reverse_if_backwards(temp); //} container = temp; }