C初级_栈和队列

1.栈

栈:先进后出的数据结构
(像个羽毛球筒、crtr+z功能)
(栈和栈区没有关联)
栈底:不做任何操作
栈顶:进行插入和删除
栈的实现:
顺序表(数组的方式):进行尾插和尾删
链表(指针的方式):头插+头删 或 尾插或尾删(头插+头删的方式要方便些)

2.队列

队列:先进先出的数据结构(类比排队的过程)
队头:进行删除
队尾:进行插入
为了方便判断队空和队满的条件,将队列的最后一个元素不存内容

3.代码实例

3.1 栈的代码

typedef struct node
{
 int data;
 struct node*next;
}NODE;
//数据入栈,数据必须插入到栈顶
void push(NODE*head,int data);
//一般删除会返回这个数据 
int pop(NODE*head);
//判断是否全部删除完成
int isEmpty(NODE* head);
int main()
{
 NODE* head=(NODE*)malloc(sizeof(NODE));
 head->next = NULL;
#if 0//实例-十进制转换成二进制并输出 
 int x = 233;
 while (x != 0)
 {
  push(head, x % 2);
  x /= 2;
 }
 while (isEmpty(head) == 0)
 {
  printf("%d", pop(head));
 }
 free(head);
#endif
#if 1//字符串逆序
 char name[] = "123456";
 int i = 0;
 while (name[i] != '\0')
 {
  push(head, name[i]);
  ++i;
 }
 while (isEmpty(head) == 0)
 {
  printf("%s", pop(head));
 }
 free(head);
#endif
 getchar();
 return 0;
}
void push(NODE*head, int data)
{
 NODE*p = (NODE*)malloc(sizeof(NODE));
 p->data = head->data;//保存数据
 //执行头插功能
 p->next = head->next;
 head->next = p;
}
int pop(NODE* head)
{
 //头删
 if (head->next == NULL)return -1;
 else
 {
  int data = head->next->data;//将要删除的数据保留
  //头删方式进行删除
  NODE* p = head->next;
  head->next = head -> next->next;
  //上一行等价于 head->next=p->next;
  free(p);
  return data;
 }
}
int isEmpty(NODE* head)
{
 return head->next == NULL;//返回0表示没删除干净,返回1表示删除干净
}

3.2 队列的代码

#include<stdio.h>
typedef struct list
{
 int arr[20];//存放数据
 int top;//队尾
 int rear;//队尾
 int size;//管理数组大小
}LIST;
void init(LIST*p)
{
 p->size = 20;
 p->top = p -> rear = 0;
}//初始化
void push(LIST*p,int data)
{
 if ((p->rear + 1)%(p->size) != p->top)//判断队尾与对头是否重合
 {
  p->arr[p->rear] = data;
  p->rear = (p->rear + 1) % (p->size);
 }
}//入队
int pop(LIST*p)
{
 int data = -1;//准备一个变量
 if (p->rear != p->top)//判断是否是空队
 {
  data = p->arr[p->top];
  p->top = (p->top + 1) % (p->size);
 }
 return data;
}//出队
int isEmpty(LIST*p)
{
 return p->rear == p->top;
}//判断是否为空
int main()
{
 LIST mylist;
 init(&mylist);
 int x = 123456;
 while (x != 0)
 {
  push(&mylist, x % 10);
  x /= 10;
 }
 while (isEmpty(&mylist) == 0)
 {
  x = x * 10 + pop(&mylist);
 }
 printf("%d",x);
 getchar();
 return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41743247/article/details/89056604