数据结构&算法-共享栈
Posted 彩色墨水
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构&算法-共享栈相关的知识,希望对你有一定的参考价值。
概念
共享栈:两个栈共享同一片存储空间,这片存储空间不单独属于任何一个栈,某个栈需要的多一点,它就可能得到更多的存储空间;
两个栈的栈底在这片存储空间的两端,当元素入栈时,两个栈的栈顶指针相向而行。
图示
运行结果
代码
using System;
namespace SharingStack
class Program
static void Main(string[] args)
SharingStackC<string> sharingStackC = new SharingStackC<string>(5);
sharingStackC.Push("龙", 1);
sharingStackC.Push("猴", 2);
Console.WriteLine(sharingStackC.Pop(1));
Console.WriteLine(sharingStackC.Pop(2));
Console.WriteLine("-----------------------------");
sharingStackC.Push("蛇", 1);
sharingStackC.Push("马", 1);
sharingStackC.Push("羊", 1);
sharingStackC.Push("虎", 1);
sharingStackC.Push("兔", 1);
sharingStackC.Push("牛", 1);
Console.WriteLine("-----------------------------");
while (sharingStackC.Stack1Count > 0)
Console.WriteLine(sharingStackC.Pop(1));
sharingStackC.Push("牛", 2);
sharingStackC.Push("鼠", 2);
sharingStackC.Push("白", 2);
Console.WriteLine("-----------------------------");
while (sharingStackC.Stack2Count > 0)
Console.WriteLine(sharingStackC.Pop(2));
/// <summary>
/// 共享栈
/// </summary>
/// <typeparam name="DataT"></typeparam>
class SharingStackC<DataT>
DataT[] totalCapacoty;
int stack1Top;
int stack2Top;
/// <summary>
/// 一号栈数量
/// </summary>
public int Stack1Count
get return stack1Top + 1;
/// <summary>
/// 二号栈数量
/// </summary>
public int Stack2Count
get return totalCapacoty.Length - stack2Top;
/// <summary>
/// 空间大小
/// </summary>
/// <param name="count"></param>
public SharingStackC(int count)
if (count < 1)
throw new Exception("空间大小要大于0");
totalCapacoty = new DataT[count];
stack1Top = -1;
stack2Top = totalCapacoty.Length;
/// <summary>
/// 入栈
/// </summary>
/// <param name="data"></param>
/// <param name="stackNumber"></param>
public void Push(DataT data, int stackNumber)
if (stack1Top + 1 == stack2Top)
Console.WriteLine("空间已满,0 无法入栈", data);
return;
if (stackNumber == 1)
stack1Top++;
totalCapacoty[stack1Top] = data;
else if (stackNumber == 2)
stack2Top--;
totalCapacoty[stack2Top] = data;
/// <summary>
/// 取数据
/// </summary>
/// <param name="stackNumber"></param>
/// <returns></returns>
public DataT Peek(int stackNumber)
if (stackNumber == 1 && stack1Top > -1)
return totalCapacoty[stack1Top];
else if (stackNumber == 2 && stack2Top < totalCapacoty.Length)
return totalCapacoty[stack2Top];
return default(DataT);
/// <summary>
/// 出栈
/// </summary>
/// <param name="stackNumber"></param>
/// <returns></returns>
public DataT Pop(int stackNumber)
if (stackNumber == 1 && stack1Top > -1)
DataT temp = totalCapacoty[stack1Top];
stack1Top--;
return temp;
else if (stackNumber == 2 && stack2Top < totalCapacoty.Length)
DataT temp = totalCapacoty[stack2Top];
stack2Top++;
return temp;
return default(DataT);
参考
以上是关于数据结构&算法-共享栈的主要内容,如果未能解决你的问题,请参考以下文章