栈函数及栈与链表的转换

来源:互联网 发布:131458淘宝信誉查询网 编辑:程序博客网 时间:2024/06/08 13:45

栈的相关函数

#include<stdio.h>#include<stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define OK 1#define ERROR 0typedef int SElemType;typedef int Status;typedef struct{SElemType *base;  /*栈底指针*/SElemType *top;   /*栈顶指针*/int stacksize;    /*当前分配长度*/}SqStack;Status InitStack(SqStack &S)/*构造一个空栈S*/{S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));    if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status GetTop(SqStack S,SElemType &e)//若栈不空,用e返回S的栈顶元素 ,并返回OK,否则ERROR{if(S.top==S.base) return ERROR;e=*(S.top--);return OK;}Status GetTop(SqStack S,SElemType &e)//栈部位空,用e返回栈顶元素{e=*(S.top--);if(e){return OK;}else{return ERROR;}}Status Pop(SqStack &S,SElemType &e)//插入元素e为新的栈顶元素{*S.top=e;S.top++;return OK;}int StackLength(SqStack S){int m=0;while(S.base=S.top){S.base++;m++;}printf(m);}void main(){}

栈转为链表

/*构建一个栈,并向栈插入n个元素 *另外使用一个指针显示栈的元素, *将栈中元素输出并赋予一个链表,链表的构建用倒插法, *用链表显示所有的元素。*/#include<stdio.h>#include<stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define OK 1#define ERROR 0typedef int SElemType;typedef int Status;typedef int ElemType;typedef struct{ElemType *base;  /*栈底指针*/ElemType *top;   /*栈顶指针*/int stacksize;    /*当前分配长度*/int number;}SqStack;typedef struct LNode /*结点*/{ElemType data;LNode *next;}LNode;typedef struct LinkList/*链表*/{LNode *head;int len;}LinkList;Status InitStack(SqStack &S)/*构造一个空栈S*/{S.base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));    if(!S.base)return 0;S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;}Status InitList(LinkList &L)   //构造一个空的线性链表L{L.head=(LNode *)malloc(sizeof(ElemType));L.head->next=NULL;if(!L.head){return OK;}else{return ERROR;}}Status Pop(SqStack &S)/*栈插入元素*/{int i,m;ElemType e;printf("请输入插入几个元素:");scanf("%d",&m);for(i=1;i<=m;i++){scanf("%d",&e);*S.top=e;    S.top++;}return m;}Status ShowSqStack(SqStack &S)//显示栈{printf("输出栈:\n");    ElemType *p;p=S.top;while(p!=S.base){p--;printf("%d  ",*p);}printf("\n");return OK;}Status ExChange(SqStack &S,LinkList &L)//栈转换为链表{LNode *p,*q;p=(LNode *)malloc(sizeof(LNode));p->next=NULL;while(S.top!=S.base){S.top--;   p->data=*S.top;q=(LNode *)malloc(sizeof(LNode));q->next=p;p=q;}L.head->next=p->next;free(p);return OK;}Status ShowLinkList(LinkList &L)//显示链表{LNode *p;p=L.head->next;printf("显示链表:");    while(p!=NULL){printf("%d  ",p->data);p=p->next;}    return OK;}void main(){    SqStack S;LinkList L;    InitStack(S);S.number=Pop(S);ShowSqStack(S);InitList(L);    ExChange(S,L);ShowLinkList(L);}


0 0
原创粉丝点击