Пример #1
0
        public void Peek_Test()
        {
            IStack <char> stack = new StackViaLinkedList <char>();

            stack.Push('A');
            stack.Push('B');
            stack.Push('C');
            stack.Push('D');
            stack.Push('E');
            stack.IsEmpty.Should().BeFalse();
            stack.Count.Should().Be(5);
            stack.Peek().Should().Be('E');
            stack.Peek().Should().Be('E');
            stack.Peek().Should().Be('E');
        }
        static void Main(string[] args)
        {
            StackViaLinkedList <int> viaLinkedList = new StackViaLinkedList <int>();
            int i = 7;

            viaLinkedList.Push(i);
            viaLinkedList.Push(i * 2);
            viaLinkedList.Push(i * 3);

            Console.WriteLine(viaLinkedList.Peek());

            Console.WriteLine(viaLinkedList.Pop());
        }
Пример #3
0
        /// <summary>
        /// Algo1: 1. Keep a stack and every time a char(other than < or >) is encountered, make stack.top.child = newelement
        /// Push this new element into the stack.
        /// 2. When a < is encountered, do nothing
        /// 3. When a > is encountered, do a pop()
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        private static TreeNode <char> CreateTreeFromExpression(char[] expression)
        {
            StackViaLinkedList <TreeNode <char> > stackForTree = new StackViaLinkedList <TreeNode <char> >();
            TreeNode <char> headOfTree = null;

            for (int expIndex = 0; expIndex < expression.Length; expIndex++)
            {
                if (expression[expIndex] == '<' || expression[expIndex] == ' ')
                {
                    // No-op
                }
                else if (expression[expIndex] == '>')
                {
                    SingleLinkedListNode <TreeNode <char> > top = stackForTree.Pop();
                    if (top == null)
                    {
                        throw new Exception("The expression is not well formed");
                    }
                }
                else
                {
                    SingleLinkedListNode <TreeNode <char> > top = stackForTree.Peek();
                    TreeNode <char> currentNode = new TreeNode <char>(expression[expIndex]);
                    if (top == null)
                    {
                        headOfTree = currentNode;
                    }
                    else
                    {
                        top.Data.Children.Add(currentNode);
                    }
                    stackForTree.Push(currentNode);
                }
            }
            // After this step the stack should be empty for a well formed expression
            if (stackForTree.Top != null)
            {
                throw new Exception("The expression is not well formed");
            }
            return(headOfTree);
        }