赞
踩
数据结构课程的练习作业,记录一下。
编译软件:Dev-C++
第一:入栈,出栈
实现代码:
#include<stdio.h>
typedef struct
{
int x[10];
int top;
}stack;
void initstack(stack *s)
{
s->top==-1;
}
int empty(stack *s)
{
if (s->top==-1)
return 1;
else return 0;
}
int full(stack *s)
{
if (s->top==10-1)
return 1;
else return 0;
}
pushstack(stack *s,int b)
{
if(full(s))
{
("栈满了\n");
return 0;
}
s->top++;
s->x[s->top]=b;
}
int popstack(stack *s)
{
if (empty(s))
{printf("该栈为空,不需要出栈\n");}
int t;t=s->x[s->top];
s->top--;
return t;
}
int main()
{stack S;
int a,i;
initstack(&S);
printf("请输入入栈元素:\n");
for(i=0;i<7;i++)
{
scanf("%d",&a);
pushstack(&S,a);}
for(i=0;i<7;i++)
printf("出栈元素为%d\n",popstack(&S));
return 0;
}
运行结果:
第二:显示栈顶元素
实现代码:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct linknode
{
int data;
struct linknode *next;
}node;
typedef struct
{
struct linknode *top;
}stack;
void init(stack *k)
{
k->top=NULL;
}
void push(stack *k,int x)
{
node *s=(node *)malloc(sizeof(node));
s->data=x;
s->next=k->top;
k->top=s;
}
int pop(stack *k)
{
if(k->top!=NULL)
{
node *q;
q=k->top;
int x=q->data;
k->top=q->next;
free(q);
return x;
}
}
int get(stack *k)
{
if(k->top!=NULL)
return k->top->data;
}
int main()
{
stack s1,*t;
int a,i;
t=&s1;
init(t);
printf("请输入入栈元素:\n");
for(i=0;i<9;i++)
{
scanf("%d",&a);
push(t,a);
}
pop(t);
printf("栈顶元素为:%d\n",get(t));
return 0;
}
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。