zoukankan      html  css  js  c++  java
  • 链栈简单操作

    /*设置一个静态变量记链表值的个数
    入栈是头插法
    */
    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    static int count=0;
    typedef struct node
    {
    int data;
    struct node *next;
    }stacknode,*linkstack;
    /*typedef struct stack
    {
    struct stack pop;
    struct stack bottom;
    }stack,*pstack;
    */
    void init (linkstack l)
    {
    l=(linkstack)malloc(sizeof(stacknode));
    if(l==NULL)
    {
    printf("分配内存失败");
    exit(-1);
    }
    l->next=NULL;

    }

    int empty(linkstack l)
    {
    if(l->next==NULL)
    {
    printf("链栈为空 ");
    return 1;
    }
    else
    {
    printf("链栈不为空 ");
    printf(" ");
    return 0;
    }
    }
    int push(linkstack l,int n)
    {
    linkstack p,q;
    p=(linkstack)malloc(sizeof(stacknode));
    q=l;
    if(p==NULL)
    {
    printf("分配内存失败");
    exit(-1);
    }
    else
    {
    p->data=n;
    p->next=q->next;
    q->next=p;
    count++;
    return 1;
    }

    }

    int pop(linkstack l)
    { int num;
    linkstack p,q;
    if(empty(l))
    {
    printf("栈为空");
    return 0;
    }
    p=l->next;
    num=p->data;
    l->next=p->next;
    free(p);
    count--;
    return 1;
    }


    void gettop(linkstack l)
    {
    printf("输出链表栈顶的值%d",l->next->data);
    printf(" ");


    }
    void tra(linkstack l)
    {
    linkstack p;
    int j=0;
    p=l->next;
    for(j=0;j<count;j++)
    {
    printf("%d ",p->data);
    p=p->next;
    }
    printf(" ");
    }


    int main()
    {
    linkstack l,p;
    l=(linkstack)malloc(sizeof(stacknode));
    init(l);
    printf("入栈6个数 ");
    push(l,1);
    push(l,2);
    push(l,3);
    push(l,4);
    push(l,5);
    push(l,6);
    tra(l);
    gettop(l);

    pop(l);
    printf("出栈后 ");
    gettop(l);
    printf(" ");
    printf(" ");
    printf(" ");
    printf("%d ",count);
    return 0;
    }

  • 相关阅读:
    mac前端解除端口占用命令
    Mac安装Brew
    Mac Webstrom 快捷键
    linux yarn安装
    js-新兴的API,最佳实践,离线应用于客户端存储
    js-高级技术
    js-Ajax与Comet
    js-错误处理与调试,JSON
    js-DOM2,表单脚本
    js-事件
  • 原文地址:https://www.cnblogs.com/mykonons/p/5867057.html
Copyright © 2011-2022 走看看