[cpp]
//利用鏈表構建棧。
//輸入1 2 3 4 5 0時輸出 5 4 3 2 1
#include<stdio.h>
#include<stdlib.h>
#define true 1
#define false 0
typedef struct node{ //建立結構體
int num;
struct node *next;
}Node;
int push(Node **head, int num) //將一個數字壓入以head為頭的堆棧
{
Node *nextNode;
if(NULL==(nextNode=(struct node *)malloc(sizeof(struct node )))){
return false;
}
nextNode->num = num;
if(NULL == *head){
nextNode->next = NULL;
*head = nextNode;
return true;
}
nextNode->next = *head;//尾插法
*head = nextNode;
return true;
}
int pop(Node **head,int *num) //出棧
{
Node *temp;
if(NULL == *head)return false;
*num = (*head)->num;
temp = (*head)->next;
free(*head);
*head = temp;
return true;
}
int main(int argc, char* argv[]) //主函數
{
int n=0,num;
Node *head;
head=NULL;
printf("Please input numbers end with 0 :\n");
while(1){ //如果不是0,壓棧
scanf("%d",&num);
if(0 == num)break;
push(&head,num);
n++;
}
while(pop(&head,&num)){ //出棧輸出
printf("%d ", num);
}
printf("\nTotal : %d\n",n);
}
作者:CreazyApple