参照教材中链栈进栈和出栈的算法,编写一个程序实现如下功能:从键盘上接收用户输入的数值,分别存入链栈中,直到用户输入任意字母结束输入。然后逐个出栈,并计算栈中所有数值之和。
common.c
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#endif // COMMON_H_INCLUDED
SEQSTACK.H
#ifndef LINKSTACK_H_INCLUDED
#define LINKSTACK_H_INCLUDED
#define StackElementType int //栈中元素数据类型为字符
//栈的结构定义
typedef struct node
{
StackElementType data;
struct node * next;
} LinkStackNode; //链栈的结构类型
typedef LinkStackNode *LinkStack ; //定义一个链栈头指针,类似顺序栈的top
//链栈初始化
void InitLinkStack(LinkStack *s);
/进栈操作。/
int Push(LinkStack top, StackElementType x);
/出栈操作。/
int Pop(LinkStack top, StackElementType *x) ;
//读取栈顶元素
int GetTop(LinkStack top, StackElementType *x) ;
#endif // LINKSTACK_H_INCLUDED
SEQSTACK.C
#include"linkstack.h"
#include"common.h"
//链栈初始化
void InitLinkStack(LinkStack *s)
{
*s=(LinkStack)malloc(sizeof(LinkStackNode));
(*s)->next=NULL; //头指针置空
}
/进栈操作。可以理解为头插法建立链表/
int Push(LinkStack top, StackElementType x) // 将数据元素x压入栈top中
{
LinkStackNode *temp;
temp=(LinkStackNode *)malloc(sizeof(LinkStackNode));
if(temp==NULL)
return(FALSE); //申请空间失败
temp->data=x;
temp->next=top->next;
top->next=temp; // 修改当前栈顶指针
return(TRUE);
}
/出栈操作。/
int Pop(LinkStack top, StackElementType x)
{
/ 将栈top的栈顶元素弹出,放到x所指的存储空间中 */
LinkStackNode * temp;
temp=top->next;
if(temp==NULL) //栈为空
return(FALSE);
top->next=temp->next; //栈顶指针移动
*x=temp->data; //读取栈顶结点元素
free(temp); //释放原栈顶结点存储空间
return(TRUE);
}
//读取栈顶元素
int GetTop(LinkStack top, StackElementType x)
{
/ 读取栈top的栈顶元素,放到x所指的存储空间中 */
LinkStackNode * temp;
temp=top->next;
if(temp==NULL) //栈为空
return(FALSE);
*x=temp->data;
return(TRUE);
}
MAIN.C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"linkstack.h"
/* 链栈的基本操作:初始化,进栈,出栈,读取栈顶 */
int main()
{
int sum = 0,tmp;
char a[100];
LinkStack Ls; //创建一个链栈
InitLinkStack(&Ls); //链栈初始化
printf(“输入数字,以空格分开,输入非数字结束输入\n”);
while(1){
gets(a);
if(strspn(a, “0123456789”)==strlen(a)) Push(Ls,atoi(a));
else break;
}
while(Pop(Ls,&tmp))sum += tmp;
printf(“总和为:%d”,sum);
return 0;
}