软件技术基础-栈和队列-上机报告 下载本文

.

姓名:阚姗蕾 学号:2010012030037

上机实验三

ex3_1:

一、程序流程说明

链栈

1)链栈结点类型定义为: typedef struct node {

int data;

struct node *next; }node_type; 2)编写进栈函数push 3)编写出栈函数pop

4)编写main函数,首先建立一空链栈;

调用进栈函数,将从键盘输入的数据元素逐个进栈,输入0结束;显示进栈后的数据元素;

调用两次出栈函数,显示出栈后的数据元素。

二、程序代码

#include #include

//定义链栈

typedef struct node_type {

int data;

struct node_type *next; } node_type;

typedef struct stack_type {

node_type *top; int length; } stack_type;

//进栈函数

void push(stack_type *s,int newnode)

.

{

node_type *p;

p=(node_type *)malloc(sizeof(node_type)); p->data=newnode; p->next=s->top; s->top=p;

s->length ++; }

//出栈函数

int pop(stack_type *s) {

node_type *p; int x;

if(s->top==NULL) {

printf(\ return(0); } else {

x=s->top->data; p=s->top;

s->top=s->top->next; free(p);

s->length--; return(x); } }

//遍历并输出

void showstack(stack_type *s) {

int i=0; int le;

stack_type *s1; node_type *p; if(s->length<=0) {

printf(\ return; }

.

s1->length=0; le=s->length;

while(i

push(s1,pop(s));

printf(\ i++; }

while(i--)//返回原栈

push(s,pop(s1));

}

int main() {

int num;

stack_type stack;

printf(\ stack.length=0;

while(scanf(\

printf(\ printf(\ showstack(&stack); printf(\length of the stack is:\\n%d\\n\

printf(\ printf(\

printf(\ printf(\

printf(\ return 0;

}

三、输入与输出

insert:number : 1 2 3 4 5 0

The length of the stack is: 5

stack after push: 5 4 3 2 1

The length of the stack is: 5