手机版
你好,游客 登录 注册
背景:
阅读新闻

C++面试题-链表栈二叉树数据结构

[日期:2013-06-15] 来源:Linux社区  作者:Linux [字体:大 中 小]

9..如何用一个数组实现三个栈

最后,让我们把抠门儿进行到底,相信看完本文,你已经从物质和精神上都升级为一个抠门儿主义者。

如果还使用交叉索引的办法,每个栈都只有N/3个空间。

让我们只好使用上个题目的第2个方法,不过这只能容纳2个栈,我们还需要一个位置存放第3个栈,不如考虑数组中间的位置——第3个栈的增长规律可以如下:

第1个入栈C的元素进mid处

 

第2个入栈C的元素进mid+1处

 

第3个入栈C的元素进mid-1处

 

第4个入栈C的元素进mid+2处

这个方法的好处是,每个栈都有接近N/3个空间。

public class NewStack

{

object[] arr;

int top1;

int top2;

int top3_left;

int top3_right;

bool isLeft;

public NewStack(int capticy)

{

arr = new object[capticy];

top1 = 0;

top2 = capticy;

isLeft = true;

top3_left = capticy / 2;

top3_right = top3_left + 1;

}

public void Push(int type, object element)

{

if (type == 1)

{

if (top1 == top3_left + 1)

throw new Exception("The stack is full");

arr[top1] = element;

top1++;

}

else if (type == 2)

{

if (top2 == top3_right)

throw new Exception("The stack is full");

top2--;

arr[top2] = element;

}

else //type==3

{

if (isLeft)

{

if (top1 == top3_left + 1)

throw new Exception("The stack is full");

arr[top3_left] = element;

top3_left--;

}

else

{

if (top2 == top3_right)

throw new Exception("The stack is full");

arr[top3_right] = element;

top3_right++;

}

isLeft = !isLeft;

}

}

public object Pop(int type)

{

object obj = null;

if (type == 1)

{

if (top1 == 0)

throw new Exception("The stack is empty");

else

{

top1--;

obj = arr[top1];

arr[top1] = null;

}

}

else if (type == 2)

{

if (top2 == arr.Length)

throw new Exception("The stack is empty");

else

{

obj = arr[top2];

arr[top2] = null;

top2++;

}

}

else //type==3

{

if (top3_right == top3_left + 1)

throw new Exception("The stack is empty");

if (isLeft)

{

top3_left++;

obj = arr[top3_left];

arr[top3_left] = null;

}

else

{

top3_right--;

obj = arr[top3_right];

arr[top3_right] = null;

}

isLeft = !isLeft;

}

return obj;

}

public object Peek(int type)

{

if (type == 1)

{

if (top1 == 0)

throw new Exception("The stack is empty");

return arr[top1 - 1];

}

else if (type == 2)

{

if (top2 == arr.Length)

throw new Exception("The stack is empty");

return arr[top2];

}

else //type==3

{

if (top3_right == top3_left + 1)

throw new Exception("The stack is empty");

if (isLeft)

return arr[top3_left + 1];

else

return arr[top3_right - 1];

}

}

}

linux
相关资讯       二叉树  链表栈 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款