栈的操作

include

include

define TRUE 1

define FALSE 0

typedef struct node
{
int data;
struct node * next;

}Stack;
Stack * initStack()
{
Stack top =(Stack)malloc(sizeof(Stack));
if(NULL!=top)
{
top->data=0;
top->next=NULL;
}
return top;

}
/* 入栈操作 */
Stack* pushStack(Stack* pHead,int Data)
{
Stack* pNewNode = (Stack*)malloc(sizeof(Stack));
if (NULL == pNewNode)
{
return NULL;
}
pNewNode->data =Data;
pNewNode->next = pHead;

pHead = pNewNode;
return pHead;

}

/* 出栈操作 */
Stack* popStack(Stack* pHead, int* outData)
{
/* 如果栈为空 */
if (NULL == pHead->next)
{
return NULL;
}

/* 把数据传出去 */
*outData = pHead->data;
Stack* pTemp = pHead;

pHead = pHead->next;

/* 把头删除 */
delete pTemp;

return pHead;

}
/* 遍历栈的操作 */
int visitStack(Stack* pHead)
{
Stack* pTemp = pHead;

/* 判断栈是否为空 */
if (NULL == pHead->next)
{
    printf("This stack is empty\n");
    return -1;
}

while (NULL != pTemp->next)
{
    printf("%d ", pTemp->data);
    pTemp = pTemp->next;
}
printf("\n");

}
int main()
{
Stack* pHead = initStack();
int n=-1;

printf("请输入数字以-1结束!\n");

 while(scanf("%d",&n)&&n!=-1) 
  /* 入栈 */
pHead = pushStack(pHead, n);
printf("入栈顺序!"); 
visitStack(pHead);
  pHead = popStack(pHead, &n);
  printf("出栈顺序!"); 
visitStack(pHead);

}

猜你喜欢

转载自blog.csdn.net/zhangwei527/article/details/78637866