⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 linkstack.c

📁 自己学习了数据结构后,写的一个关于链栈的实现的联系程序,希望大家指教
💻 C
字号:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define maxsize 100

//定义链栈的结构体
typedef struct node
{
    int data;
    struct node *next;
}*linkstack,stacknode;

//置空栈
linkstack init_linkstack()
{
    linkstack top;
    top=(linkstack)malloc(sizeof(stacknode));
    top->next=NULL;
    return top;
}

//判空栈
int empty_linkstack(linkstack top)
{
    if(top->next==NULL)
    {
        printf("NULL stack!\n");
        return -1;
    }
    else
        return 1;
}

//入栈
linkstack push_linkstack(linkstack *top,int x)
{
    stacknode *s;
    s=(stacknode *)malloc(sizeof(stacknode));
    s->data=x;
    s->next=*top;
    *top=s;
    return *top;
}

//出栈
linkstack pop_linkstack(linkstack top,int data[],int n)
{
    stacknode *p;
    int i;
    if(top==NULL)
        return NULL;
    else
    {
        for(i=0;i<n;i++)
    	{
        data[i]=top->data;
        p=top;
        top=top->next;
        free(p);
    	}
        return top;
    }
}

//打印栈中元素
void print(linkstack top)
{
    stacknode *r;
    r=top;
    while(r->next!=NULL)
    {
        printf("%d ",r->data);
        r=r->next;
    }
    printf("\n");
}

//主函数
void main()
{
    linkstack top;
    int i,x,m,n=0;
    int a[maxsize];
    int *p=NULL;
    top=init_linkstack();
    printf("Input data(End flag:-1):\n");
    
    while(1)
    {   scanf("%d",&x);
        if(x==-1)
        break;
        else
            push_linkstack(&top,x);
        n++;
    }
    printf("%d data in the stack:\n",n);
    print(top);
    printf("input pop number:\n");
    scanf("%d",&m);
    if(m>n)
        printf("To large ,input again:\n",n);
    else{
    printf("The data of POP:\n");
    pop_linkstack(top,a,m);
    for(i=0;i<m;i++)
        printf("%d ",a[i]);
    printf("\n");}
    getch();
}    
   

    
  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -