先確定一個小目標:
建立一個數棧,數據類型為整型數據,分別用順序棧和鏈棧完成以下功能:
1、編寫取棧頂元素、入棧、出棧算法;
2、通過進制轉化驗證上述是三個算法(原數據,擬轉化的進制從鍵盤輸入,輸出轉化后的結果);
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Stack
{
int data;
struct Stack * next;
}Stack;
Stack * InitStack()//初始化
{
Stack * p=(Stack*)malloc(sizeof(Stack));
if(p!=NULL)
{
p->data=0;
p->next=NULL;
}
return p;
}
Stack* push(Stack *head,int x)
{
Stack *p=(Stack *)malloc(sizeof(Stack));
if(p==NULL)
{
return NULL;
}
p->data=x;
p->next=head;
head=p;
return head;
}
Stack * pop(Stack *head)
{
if(head->next==NULL)
{
return NULL;
}
Stack *p;
p=head;
head=head->next;
free(p);
//printf("%d",head->data);
return head;
}
int top(Stack * head,int *l)
{
if(head->next==NULL)
return -1;
*l=head->data;
printf("%d",head->data);
return 0;
}
int visit(Stack * head)
{
Stack *p=head;
if(p->next==NULL)
{
printf("棧為空\n");
return -1;
}
while(p->next!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int StackEmpty(stack *head)//判斷棧是否為空
{
if(head==NULL)
{
printf("棧為空");
}
else
return 1;
}
int main()
{
int a,b,x,l;
scanf("%d",&b);
Stack * s;
s=InitStack();
while(b!=0)
{
a=b%2;
b=b/2;
s=push(s,a);
}
visit(s);
}