CCI_Q3.1

本文参考该作者文章当作编程笔记:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

Q:

你如何只用一个数组实现三个栈?

思路:

创建一个结构数组sn,数组中的每个元素将是这样一个结点,它保存当前位置的值item,和指向上一个结点的索引preindex。这样弹出该栈的栈顶值时,可以找到上一个该栈元素。

注意:当弹出栈顶值时,如果该栈顶索引小于数组当前的索引C,那么将C指向该栈顶索引。这样可以不浪费空间。

CODE:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define N 10
 4 #define EMPTY -2
 5 typedef struct stackNode
 6 {
 7     int item;
 8     int preindex;//该数据的前一个数据的位置。
 9 }stackNode;
10 int C,sntop[3];stackNode *sn;
11 void initStackNode(int n)
12 {
13     sn=malloc(sizeof(stackNode)*n);
14     int i;
15     for(i=0;i<N;i++)
16     {
17         sn[i].preindex=EMPTY;//代表空位置。
18     }
19     C=0;//数组下标
20     sntop[0]=sntop[1]=sntop[2]=-1;//3个栈的栈顶位置
21 }
22 void stackNodePush(int i,int stacknum)
23 {
24     if(C==N)//栈满
25         return;
26     if(sn[C].preindex==EMPTY)
27     {
28         sn[C].item=i;
29         sn[C].preindex=sntop[stacknum];//将新数据指向前一个位置。
30         sntop[stacknum]=C;//新的栈顶位置
31     }
32     else
33     {
34         int i;
35         for(i=C+1;i<N;i++)//找到空位置
36         {
37             if(sn[i].preindex==EMPTY)
38                 break;
39         }
40         C=i;
41         sn[C].item=i;
42         sn[C].preindex=sntop[stacknum];
43         sntop[stacknum]=C;
44     }
45     ++C;
46 }
47 int stackNodePop(int stacknum)
48 {
49     int t=EMPTY;
50     if(sntop[stacknum]==-1)//该栈为空
51         return EMPTY;
52     if(sntop[stacknum]<C)//如果该栈顶在C的下面,将C指向它
53     {
54         C=sntop[stacknum];
55         sntop[stacknum]=sn[C].preindex;
56         sn[C].preindex=EMPTY;
57         t=sn[C].item;
58     }
59     else//否则弹出该栈顶数据,并将改位置设为空
60     {
61         int a=sntop[stacknum];
62         sntop[stacknum]=sn[a].preindex;
63         sn[a].preindex=EMPTY;
64         t=sn[a].item;
65     }
66     return t;
67 }
68 int main()
69 {
70     initStackNode(N);
71     stackNodePush(2,2);
72     stackNodePush(1,1);
73     stackNodePush(0,0);
74     stackNodePush(2,2);
75     stackNodePush(1,1);
76     stackNodePush(2,2);
77     stackNodePush(0,0);
78     stackNodePush(2,2);
79     stackNodePush(1,1);
80     stackNodePush(1,1);//插入了10个数据
81     stackNodePop(2);
82     stackNodePop(0);//弹出了2个
83     stackNodePush(0,0);
84     stackNodePush(0,0);//又插入了2个
85     int i;
86     for(i=0;i<3;++i)
87     {
88         int t;
89         printf("%d:",i);
90         while((t=stackNodePop(i))!=EMPTY)
91             printf("\t%d",t);
92         printf("\n");
93 
94     }
95 }

 

 

posted @ 2014-03-10 10:48  哈士奇.银桑  阅读(146)  评论(0编辑  收藏  举报