c/c++语言开发共享详解C语言数据结构之栈

目录栈的链式实现主要内容代码实现:总结栈的链式实现主要内容(1) 栈包含7个元素,依次是67,3,88,6,1,7,0,采用尾插入法创建 栈,为该栈设置两个指针,一个bottom和一个top指针;(2

目录
  • 栈的链式实现
    • 主要内容
    • 代码实现:
  • 总结

    栈的链式实现

    主要内容

    (1) 栈包含7个元素,依次是67,3,88,6,1,7,0,采用尾插入法创建 栈,为该栈设置两个指针,一个bottom和一个top指针;

    (2) 入栈函数push,该函数完成向栈中插入元素的功能,利用push函数,将数字-9插入到栈内,并将栈里的元素遍历;

    (3) 出栈函数pop,该函数完成从栈中删除元素的功能,利用pop函数,删除此时栈里面的3个元素,并遍历栈;

    (4) 函数length,求出此时栈内元素的个数。

    代码实现:

    #include<stdio.h>  #include<stdlib.h>  struct node  {  	int date;  	struct node *next;  };  struct stack  {  	struct node *bottom;  	struct node *top;  }s;  struct stack *creat(struct stack *s);              //创建栈  void  push(struct stack *s,int e);   //入栈  void print(struct stack *s);       //打印输出  void pop(struct stack *s);         //出栈  void length(struct stack *s);      //输出栈的长度  int main()  {  	struct stack *s;  	int e;  	s=creat(s);  	push(s,67);  	push(s,3);      push(s,88);      push(s,6);      push(s,1);      push(s,7);      push(s,0);      printf("初始栈元素为:");      print(s);      printf("n");      printf("n");      push(s,-9);      printf("插入元素后:");      print(s);      printf("n");      printf("n");      pop(s);      pop(s);      pop(s);      printf("删除元素后:");      print(s);      printf("n");      printf("n");      length(s);  	return 0;  }  struct stack *creat(struct stack *s)  {  	s=(struct stack *)malloc(sizeof(struct stack ));  	s->bottom=s->top=(struct node *)malloc(sizeof(struct node));  	s->top->next=null;      s->bottom->next=null;  	return s;  }  void  push(struct stack *s,int e)//进栈  {      struct node *p;      p=(struct node *)malloc(sizeof(struct node));  	p->date=e;  	p->next=null;  	s->top->next=p;  	s->top=p;  }  void pop(struct stack *s)// 出栈  {     struct node *p,*q;     p=s->bottom;     while(p->next!=null)       {            q=p;            p=p->next;                   }      q->next=null;      s->top=q;  }  void print(struct stack *s)//打印输出  {      struct node *p = s->bottom->next;  	while(p!=null)  	{  		printf("%4d",p->date);  		p=p->next;  	}  }    void length(struct stack *s)//计算长度  {     struct node *p=s->bottom->next;     int i=0;     while(p!=null)      {          i++;          p=p->next;      }     printf("此时栈的长度为:%4d",i);  }     

    总结

    本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注<计算机技术网(www.ctvol.com)!!>的更多内容! 

    需要了解更多c/c++开发分享详解C语言数据结构之栈,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

    本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

    ctvol管理联系方式QQ:251552304

    本文章地址:https://www.ctvol.com/c-cdevelopment/1038414.html

    (0)
    上一篇 2022年1月26日
    下一篇 2022年1月26日

    精彩推荐