C#数据结构-栈
棧是一種特殊的線性結(jié)構(gòu),是一種運(yùn)算受限的數(shù)據(jù)結(jié)構(gòu),棧的特點(diǎn)就是是先進(jìn)后出,跟我們的乒乓球筒,羽毛球筒一樣,先放進(jìn)去的在棧底,后放進(jìn)去的稱之為頂點(diǎn)或者棧頂。
這里,我們用兩種方式表達(dá)棧的運(yùn)用,順序表和鏈表。
順序棧
這里標(biāo)記頂點(diǎn),因?yàn)闂5倪@種先進(jìn)后出的特殊結(jié)構(gòu),入棧和出棧都是從頂點(diǎn)操作的。
/// <summary>/// 順序棧/// </summary>class LinkStack{const int Maxsize = 100;public string[] data;public int top;public LinkStack(){data = new string[Maxsize];top = -1;}#region 判斷是否為空棧 O(1)public bool StackEmpty(){return (top == -1);}#endregion#region 進(jìn)棧 O(1)public bool Push(string values){//滿棧無(wú)法進(jìn)棧if (top >= Maxsize-1){return false;}top++;data[top] = values;return true;}#endregion#region 出棧 O(1)public bool Pop(ref string values){//判斷是否為空棧if (StackEmpty()){return false;}values = data[top];top--;return true;}#endregion#region 獲取頂點(diǎn)值 O(1)public bool GetTop(ref string values){if (StackEmpty()){return false;}values = data[top];return true;}#endregion}
鏈?zhǔn)綏?#xff1a;
這里也是一樣,保存頭部,每次出棧入站都是操作頭部。
/// <summary>/// 鏈?zhǔn)綏4鎯?chǔ)結(jié)構(gòu)/// </summary>class LinkListStack{public string data;public LinkListStack next;}/// <summary>/// 鏈?zhǔn)綏5牟僮?// </summary>class LinkStackClass{LinkListStack head = new LinkListStack();public LinkStackClass(){head.next = null;}#region 判斷鏈?zhǔn)綏J欠駷榭?O(1)public bool StackEmpty(){return (head.next == null);}#endregion#region 入棧 O(1)public void Push(string values){LinkListStack stacks = new LinkListStack();//頭部進(jìn)棧stacks.data = values;stacks.next = head.next;head.next = stacks;}#endregion#region 出棧 O(1)public bool Pop(ref string values){LinkListStack stack;//判斷棧是否為空if (head.next==null)//StackEmpty(){return false;}//出棧從頭部出棧stack = head.next;values = stack.data;head.next = stack.next;stack = null;return true;}#endregion#region 取棧的頂點(diǎn) O(1)public bool GetTop(ref string values){LinkListStack stack;//判斷棧是否為空if (head.next == null)//StackEmpty(){return false;}stack = head.next;values = stack.data;return true;}#endregion}
/// <summary>/// 鏈?zhǔn)綏4鎯?chǔ)結(jié)構(gòu)/// </summary>class LinkListStack{public string data;public LinkListStack next;}/// <summary>/// 鏈?zhǔn)綏5牟僮?// </summary>class LinkStackClass{LinkListStack head = new LinkListStack();public LinkStackClass(){head.next = null;}#region 判斷鏈?zhǔn)綏J欠駷榭?O(1)public bool StackEmpty(){return (head.next == null);}#endregion#region 入棧 O(1)public void Push(string values){LinkListStack stacks = new LinkListStack();//頭部進(jìn)棧stacks.data = values;stacks.next = head.next;head.next = stacks;}#endregion#region 出棧 O(1)public bool Pop(ref string values){LinkListStack stack;//判斷棧是否為空if (head.next==null)//StackEmpty(){return false;}//出棧從頭部出棧stack = head.next;values = stack.data;head.next = stack.next;stack = null;return true;}#endregion#region 取棧的頂點(diǎn) O(1)public bool GetTop(ref string values){LinkListStack stack;//判斷棧是否為空if (head.next == null)//StackEmpty(){return false;}stack = head.next;values = stack.data;return true;}#endregion}
總結(jié)
- 上一篇: spring 使用XML配置开发Spri
- 下一篇: SQLServer引擎优化顾问