Documente Academic
Documente Profesional
Documente Cultură
Exercise 6-3.
3. Write a program to implement 2 stacks in one array where the first stack will start from 0th position and the second stack will start from the last position. public class stack2 { private int [ ] stack_arr; private int top1; private int top2; //////// // construct empty List with specified name public stack2(int MAX) { stack_arr = new int [MAX]; 1
top1 = -1; top2 = MAX; } // end constructor ///////////////////////////////////////////// public void push( int stack_No) { int pushed_item; if (stack_No==1) { Console.WriteLine("newtop1={0} top2={1}", top1+1,top2); if ( top1== (top2 - 1)) Console.WriteLine("Stack1 overflow"); else { Console.WriteLine ("Enter the item to be pushed in stack1:"); pushed_item=Convert.ToInt32( Console.ReadLine()); top1 = top1+1; stack_arr[top1] = pushed_item; } } if (stack_No==2) { Console.WriteLine("newtop2={0} top1={1}", top2 -1, top1); if ( top2== (top1 + 1)) Console.WriteLine("Stack2 overflow"); else { Console.WriteLine ("Enter the item to be pushed in stack2:"); pushed_item=Convert.ToInt32( Console.ReadLine()); top2 = top2-1; stack_arr[top2] = pushed_item; } } }/*End of push( ) */ /*---------------------------------------*/ /////////////////////////////////////////// public void pop(int stack_No ) { if (stack_No==1) { Console.WriteLine("newtop1={0} top2={1}", top1 - 1, top2); if ( top1 == -1) Console.WriteLine("Stack1 underflow "); else { Console.WriteLine("Popped element stack1 is {0}", stack_arr[top1]); top1 = top1-1; } } if (stack_No==2) 2
{ Console.WriteLine("newtop2={0} top1={1}", top2 + 1, top1 ); if ( top2 == (stack_arr .Length )) Console.WriteLine("Stack2 underflow "); else { Console.WriteLine("Popped element stack2 is {0}", stack_arr[top2]); top2 = top2+1; } } }/*End of pop( ) */ /////////////////////////////////////// } // end class stack2
Exercise 6-4.
4. Write a program of stack to display the elements in FIFO manner. Stack public void push(int data) { top = new node(data,top); }/*End of push */ ///////////////////////////////////// public int pop() { int i=-1; if (top == null) Console.WriteLine("Stack is empty"); else { i = top.Info; Console.WriteLine("Popped item is: {0}",i ); top = top.Next; } return i; }/*End of pop() */ /////////////////////////////////////////////////////////////////// public void display() { node ptr=top; if (top == null) Console.WriteLine("Stack is empty"); else { Console.WriteLine("Stack elements :"); while (ptr!= null) { Console.WriteLine(ptr.Info); ptr = ptr.Next; } }//end else 3
}/*End of display() */ ////////////////////////////////////////////////////////////////////// public void display_FIFO( ) { if (this.top == null) { Console.WriteLine("Stack is empty"); return; } stack tmp = new stack(); while (this.top != null) tmp.push(this.pop()); tmp.display(); while (tmp.top != null) this.push(tmp.pop()); }/*End of display_FIFO() */ //////////////////////////////////////////////////