#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int number;
struct node *next;
}Node,*pNode;
typedef struct stack
{
pNode top;
pNode bottom;
}Stack,*pStack;
void InitStack(pStack p)
{
p->top = (pNode*)malloc(sizeof(Node));
if ( !p )
{
printf("內存分配失敗......");
exit(-1);
}
p->bottom = p->top;
p->top->next = NULL;
}
int Push(pStack p,int data)
{
pNode pNew = (pNode*)malloc(sizeof(Node));
if ( !pNew )
{
printf("內存分配失敗......");
exit(-1);
}
pNew->number = data;
pNew->next = p->top;
p->top = pNew;
return 1;
}
int Pop(pStack p)
{
pNode pSwap = NULL;
int val;
if ( Empty(p) )
{
exit(-1);
}
val = p->top->number;
pSwap = p->top;
p->top = p->top->next;
free(pSwap);
return val;
}
int Empty(pStack p)
{
if ( p->top == p->bottom )
{
return 1;
}
else
{
return 0;
}
}
void TravseStack(pStack p)
{
pNode pNew;
pNew = p->top;
while ( pNew != p->bottom )
{
printf("%d==>",pNew->number);
pNew = pNew->next;
}
printf("END\n");
}
int GetLength(pStack p)
{
int count=0;
pNode pNew;
pNew = p->top;
while ( pNew != p->bottom )
{
pNew = pNew->next;
count++;
}
return count;
}
int GetTop(pStack p)
{
if ( Empty(p) )
{
return -1;
}
return p->top->number;
}
void DestoryStack(pStack p)
{
pNode pSwap = NULL;
while ( p->top != p->bottom )
{
pSwap = p->top;
p->top = p->top->next;
free(pSwap);
}
}
int main(void)
{
Stack s; // 定義一個棧
int k=1,choose;
int i,r,r1,r2;
int num;
int data; // 臨時保存用戶輸入的數據
int re_num; // 保存Pop函數的返回值
while ( k == 1 )
{
puts("++++++++++++++++++++++++++++++++++++++++++++++++");
puts("++ 主菜單:\n++");
puts("++ 1. 初始化棧\n++");
puts("++ 2. 元素入棧\n++");
puts("++ 3. 元素出棧\n++");
puts("++ 4. 獲取棧頂元素\n++");
puts("++ 5. 遍歷棧元素\n++");
puts("++ 6. 棧長度\n++");
puts("++ 7. 銷燬棧\n++");
puts("++ 0. 退出\n++");
puts("++++++++++++++++++++++++++++++++++++++++++++++++");
scanf("%d",&choose);
flushall();
if ( choose>=0 && choose<=7 )
{
switch(choose)
{
case 1:
InitStack(&s);
printf("\n");
break;
case 2:
do{
printf("你想輸入幾個數據啊:");
r = scanf("%d",&num);
flushall();
if ( r == 1 )
{
for ( i =0 ; i<num ; i++ )
{
do
{
printf("第 %d 個數:",i+1);
r1 = scanf("%d",&data);
flushall();
if ( r1 == 1 )
{
if (Push (&s,data)) // 調用Push函數
{
continue;
}
else
{
printf("進行進棧操作失敗!\n");
exit(-1);
}
}
}while ( !(r1 == 1) );
}
}
}while ( !(r == 1) );
printf("\n");
break;
case 3:
do{
printf("你想去掉幾個數啊: ");
r2 = scanf("%d",&data);
flushall();
if ( r2 == 1 && data <= num)
{
printf("你去掉的數字是:");
for (i = 0; i < data;i++)
{
re_num = Pop (&s); //調用Pop函數,並把返回值賦給re_num;
printf("%d ",re_num);
}
}
}while ( !( r2 == 1 && data <= num) );
printf("\n");
break;
case 4:
printf("棧頂元素是:%d\n",GetTop(&s));
printf("\n");
break;
case 5:
TravseStack(&s); // 調用遍歷函數
printf("\n");
break;
case 6:
printf("棧的長度爲:%d\n",GetLength(&s));
printf("\n");
break;
case 7:
DestoryStack(&s); // 調用清空棧函數
printf("遍歷下看看棧清空沒····\n");
TravseStack(&s);
printf("\n");
break;
case 0:
DestoryStack(&s);
k = 0;
break;
}
}
}
getch();
return 0;
}