栈(C#)

来源:互联网 发布:流星网络电视vip破解版 编辑:程序博客网 时间:2024/05/18 02:51

栈的主要机制是用数组来实现,也可以用链表来实现.

栈只允许访问一个数据项:即最后插入的数据项.移出这个数据项后才能访问倒数第二个数据项.

栈的概念和实现它的内部数据结构是完全分开的.


using System;class StackX{    private int maxSize;    //size of stack array    private long[] stackArray;    private int top;        //top of stack    public StackX(int s)    // constructor    {        maxSize = s;        //set array size        stackArray = new long[maxSize];     //create array        top = -1;       //no item yet    }    public void Push(long j)    //put item on top of stack    {        stackArray[++top] = j;   //increment top, insert item    }    public long Pop()           //take item from top of stack    {        return stackArray[top--];   //access item, decrement top    }    public long Peek()      //peek at top of stack    {         return stackArray[top];    }    public bool IsEmpty()    //true if stack is empty    {         return (top == -1);    }    public bool IsFull()    //true if stack is full    {         return (top == maxSize-1);    }}  //end class stackclass StackApp{    static void Main(string[] args)    {        StackX theStack = new StackX(10);   //make new stack        theStack.Push(20);      //push items onto stack        theStack.Push(40);        theStack.Push(60);        theStack.Push(80);        while (!theStack.IsEmpty()) // until it's empty        {                           //delete item from stack            long value = theStack.Pop();            Console.Write(value);   // display it            Console.Write(" ");        }   // end while        Console.WriteLine();        Console.ReadLine();    }   // end main}   // end class StackX



//栈实例:单词逆序using System;class StackX{    private int maxSize;    private char[] stackArray;    private int top;    public StackX(int max)  //constructor    {        maxSize = max;        stackArray = new Char[maxSize];        top = -1;    }    public void Push(char j)    //put item on top of stack    {        stackArray[++top] = j;    }    public char Pop()   //take item from top of stack    {         return stackArray[top--];    }    public char Peek()  //peek at top of stack    {         return stackArray[top];    }    public bool IsEmpty()   // true if stack is Empty    {         return (top == -1);    }} // end class StackXclass Reverser{    private string input;   //input string    private string output;  //output string    public Reverser(string inStr)  //constructor    {        input = inStr;    }    public string DoRev()  //reverse the string    {        int stackSize = input.Length; //get max stack size        StackX theStack = new StackX(stackSize);    //make stack        for (int j = 0; j < input.Length; j++ )        {            char ch = input[j];  //get a char from input            theStack.Push(ch);  //push it        }        output = "";        while (!theStack.IsEmpty())        {            char ch = theStack.Pop();   // pop a char            output = output + ch;       //append to output        }        return output;    } // end DoRev();}class ReverseApp{    static void Main(string[] args)    {        String input, output;                while (true)        {            Console.Write("Enter a string:");            input = Console.ReadLine();     //read a string from kbd            if (input.Length == 0)  //quite if [enter]                break;            Reverser theReverser = new Reverser(input); // make a Reverser            output = theReverser.DoRev();   // use it            Console.WriteLine("Reversed:{0}", output);            Console.ReadLine();        } // end while     }   // end main}


using System;//实例,分隔符匹配class StackX{    private int maxSize;    private char[] stackArray;    private int top;    public StackX(int s)     //constructor    {        maxSize = s;        stackArray = new char[maxSize];        top = -1;    }    public void Push(char j)    //put item on top of stack    {        stackArray[++top] = j;    }    public char Pop()       //take item from top of stack    {        return stackArray[top--];    }    public char Peek()      //peek at top of stack    {         return stackArray[top];    }    public bool IsEmpty()   //true if stack is empty    {        return (top == -1);    }   } // end class StackXclass BracketChecker{    private string input;               //input string    public BracketChecker(String inner)    //constructor    {        input = inner;    }    public void Check()    {        int stackSize = input.Length;   //get max stack size        StackX theStack = new StackX(stackSize);    //make stack        for (int j = 0; j < input.Length; j++)  //get chars in trun        {            char ch = input[j];            switch (ch)            {                 case '{':   //opening symbols                case '[':                case '(':                    theStack.Push(ch);      //push them                    break;                case '}':   //chosing symbols                case ']':                case ')':                    if (!theStack.IsEmpty())     // if stack not empty                    {                        char chx = theStack.Pop();      //pop and check                        if ((ch == '}' && chx != '{') ||                            (ch == ']' && chx != '[') ||                            (ch == ')' && chx != '('))                            Console.WriteLine("Error: at {0}", j);                    }                    else        //prematurely empty                        Console.WriteLine("Error: at {0}", j);                    break;                default:        //no action on other characters                    break;            }//end switch        }//end for    //at this point, all characters have been processed        if(!theStack.IsEmpty())        {            Console.WriteLine("Error: missing right delimiter");        }//end check    }//end class BracketChecker   }class BracketsApp{    static void Main(string[] args)    {        string input;        while (true)        {            Console.WriteLine("Enter string containing delimeters:");            input = Console.ReadLine(); //read a string kbd            if (input == null)          //quit if [Enter]                break;                                        //make a BracketChecker            BracketChecker theChecker = new BracketChecker(input);            theChecker.Check();         //check brackets        }//end while        Console.ReadLine();    }//end main}

//用链表实现的栈(ADT)using System;class Link{    public long dData;  //data item    public Link next;   //next link in list    public Link(long dd)    //constructor    {        dData = dd;    }    public void DisplayLink()    //display ourself    {         Console.Write(dData + " ");    }}//end class Linkclass LinkList{    private Link first;     //ref to first item on list    public LinkList()       //constructor    { first = null; }       //no items on list yet    public bool IsEmpty()       //true if list is empty    { return (first == null); }    public void InsertFirst(long dd)    //insert at start of list    {                                   //make new link        Link newLink = new Link(dd);        newLink.next = first;           //newLink --> old first        first = newLink;                //first -->newLink    }    public long DeleteFirst()   //delete first item    {                           //(assume list not empty)        Link temp = first;      //save reference to link        first = first.next;     //delete it: first-->old next        return temp.dData;      //return delete link    }    public void DisplayList()    {        Link current = first;   //start at beginning of list        while (current != null)     //until end of list        {            current.DisplayLink();  //print data            current = current.next; //move to next link        }        Console.WriteLine();    }}class LinkStack{    private LinkList theList;    public LinkStack()      //constructor    {        theList = new LinkList();    }    public void Push(long j)    //put item on top of stack    {        theList.InsertFirst(j);    }    public long Pop()       //take item from top of stack    {        return theList.DeleteFirst();    }    public bool IsEmpty()   //true if stack is empty    {        return theList.IsEmpty();    }    public void DisplayStack()    {        Console.Write("Stack (top -->bottom):");        theList.DisplayList();    }}//end class LinkStackclass LinkStackApp{    public static void Main(string[] args)    {        LinkStack theStack = new LinkStack();   //make stack        theStack.Push(20);              //push items        theStack.Push(40);        theStack.DisplayStack();        //display stack        theStack.Push(60);              //push items        theStack.Push(80);        theStack.DisplayStack();        //display stack        theStack.Pop();     //pop items        theStack.Pop();        theStack.DisplayStack();        //display stack        Console.ReadLine();    }//end main}//end class LinkStackApp