/// <summary> /// Takes input queue and pushes items onto stack. /// </summary> /// <returns> The stack containing queue items.</returns> /// <param name="Q">Original queue.</param> public LinkedStack <T> QueueToStack(LinkedQueue <T> Q) { LinkedStack <T> S = new LinkedStack <T>(); Node current = Q.First; while (current.Next != null) { Node removed = current; S.Push(removed.Value); Q.Dequeue(); current = current.Next; } return(S); }
/// <summary> /// Takes input queue and pushes items onto stack. /// </summary> /// <returns>The stack with queue items.</returns> /// <param name="q">Original queue.</param> public LinkedStack <T> QueueToStack(LinkedQueue <T> q) { LinkedStack <T> s = new LinkedStack <T>(); Node current = q.First; while (current.Next != null) { Node removed = current; s.Push(removed.Value); q.Dequeue(); current = current.Next; } return(s); }
static void Main() { LinkedStack <string> s = new LinkedStack <string>(); string readPath = "/your_path/here/input.txt"; string writePath = "/Users/trevorheehs/"; if (!File.Exists(readPath)) { throw new ArgumentException("File not found."); } // input text to string array where each element is one line. string[] linesOfText = File.ReadAllLines(readPath); // Iterate through string array and push lines onto stack. foreach (string line in linesOfText) { s.Push(line); } // To test stack input...comment out if needed. s.Print(); // Write to same string array by popping off stack, reversing the array text. for (int i = 0; i < linesOfText.Length; i++) { string newLine = s.Peek(); linesOfText[i] = newLine; s.Pop(); } // Uncomment to test reversed array... //foreach (var line in linesOfText) //{ // Console.WriteLine(line); //} File.WriteAllLines(writePath, linesOfText); //The Upshot: I could place a lot of this in a method, but you said program. //O(n) time and O(n) space. }