链栈的基本操作-数据结构

来源:互联网 发布:多益网络股票代码 编辑:程序博客网 时间:2024/05/21 06:34

链栈写的跟头插法建链表一样,就是头插法建起来,然后就是链表的基本操作了。

例代码:

#include<stdio.h>#include<string.h>#include<malloc.h>#define OK 1#define ERROR 0#define VOERFLOW -1typedef int Status;typedef int Elemtype;typedef struct LNode{Elemtype data;struct LNode *next;}LNode,*Linklist;bool EmptyStack(Linklist s){    if(s->next==NULL) return true;    else return false;}Status InitStack(Linklist &s){s=(LNode*)malloc(sizeof(LNode));s->next=NULL;return OK;}Status Pushstack(Linklist &s,Elemtype e){    Linklist p;    p=(LNode*)malloc(sizeof(LNode));    p->data=e;    p->next=s->next;    s->next=p;    return OK;}Status DisplayStack(Linklist s){    Linklist p;    p=s->next;    while(p!=NULL)    {        printf("%d ",p->data);        p=p->next;    }    printf("\n");    return OK;}int StackLength(Linklist s){    int i;    Linklist p;    p=s->next;    i=0;    while(p!=NULL)    {        i++;        p=p->next;    }    return i;}Elemtype GetTopelem(Linklist s,Elemtype &e){    if(s->next==NULL) return ERROR;    e=s->next->data;    return OK;}Status PopStack(Linklist &s){    if(EmptyStack(s)) return ERROR;    Linklist p;    p=(LNode*)malloc(sizeof(LNode));    p=s->next;    s->next=p->next;    free(p);}Status ClearStack(Linklist &s){    Linklist p,q;    p=s->next;    while(p!=NULL)    {        q=p;        s->next=p->next;        p=p->next;        free(q);    }    return OK;}int main(){Linklist stack;int n,i,len;Elemtype e;InitStack(stack);printf("Input n and the elem:");scanf("%d",&n);for(i=0;i<n;i++)    {        scanf("%d",&e);        Pushstack(stack,e);    }    DisplayStack(stack);    len=StackLength(stack);    printf("The length of the stack is %d.",len);    GetTopelem(stack,e);    printf("The top elem is %d.\n",e);    PopStack(stack);    GetTopelem(stack,e);    printf("The top elem is %d.\n",e);    ClearStack(stack);    if(EmptyStack(stack)) printf("The stack is empty now!\n");    return 0;}


0 0
原创粉丝点击