考研数据结构——栈和队列

古城微笑少年丶 2023-07-04 06:24 39阅读 0赞

怕什么前路太长,进一寸有一寸的欢喜

栈:是线性表。是只能在一端进行插入和删除的线性表。

栈的基本操作:

  1. InitStack(&S):初始化
  2. StackEmpty(S):判空
  3. Push(&S,x)插入元素入栈
  4. Pop(&S,&x)取出栈顶元素
  5. GetTop(S,&x)读取栈顶元素
  6. ClearStack(&S):销毁栈

顺序栈:

  1. #define MaxSize 50
  2. typedef struct{
  3. Elemtype data[MaxSize];
  4. int top;
  5. }SqStack;
  6. 初始化:
  7. void InitStack(&s){
  8. s.top = -1;
  9. }
  10. 判空:
  11. bool StackEmpty(S){
  12. if(S.top==-1) teturn true;
  13. else return false;
  14. }
  15. 入栈:
  16. bool Push(SqStack &S,Elemtype x){
  17. if(S.top==MaxSize-1) return false;
  18. S.data[++S.top] = x;
  19. teturn true;
  20. }
  21. 出栈:
  22. bool Pop(SqStack &S,Elemtype &x){
  23. if(S.top==-1) return false;
  24. x = S.data[S.top--];
  25. return true;
  26. }

共享栈:两个栈空间相互调节,只有在整个存储空间被占满时才发生上溢。

链栈:不存在栈满上溢的情况,用单链表实现,所有操作都是在单链表表头进行,链栈没有头结点 。

队列:是线性表,是从尾进从头出的线性表。

  1. #define MaxSize 50
  2. typedef struct{
  3. Elemtype data[MaxSize]; //队列是用数组定义的。
  4. int front,rear;
  5. }SqQueue;
  6. 循环队列:
  7. 初始化:
  8. void InitQueue(SqQueue &Q){
  9. Q.rear = Q.front = 0;
  10. }
  11. 判断空:
  12. bool isEmpty(Q){
  13. if(Q.rear==Q.front) return true;
  14. else return false;
  15. }
  16. 入队:
  17. bool EnQueue(SqQueue &Q,Elemtype x){
  18. if((Q.rear+1)%MaxSize==Q.front) return false;
  19. Q.data[rear] = x;
  20. Q.rear = (Q.rear+1)%MaxSize;
  21. return true;
  22. }
  23. 出队:
  24. bool DeSqQueue(SqQueue &Q,Elemtype x){
  25. if(Q.rear==Q.front) return false;
  26. s = Q.data[rear];
  27. Q.rear = (Q.rear+1)%MaxSize;
  28. return true;
  29. }

链队:带有头指针和尾指针的单链表。

  1. 链式存储定义:
  2. typedef struct LinkNode{
  3. Elemtype data[];
  4. struct LinkNode *next;
  5. }LinkNode;
  6. typedef struct{
  7. LinkNode *front,*rear;
  8. }LinkQueue;
  9. 初始化:
  10. void InitQueue(LinkQueue &Q){
  11. Q.front = ()malloc();
  12. Q.front->next = NULL;
  13. }
  14. 判空:
  15. bool IsEmpty(LinkQueue &Q){
  16. if(Q.front==Q.rear) return true;
  17. return false;
  18. }
  19. 入队:
  20. void InsertLinkQueue(LinkQueue &Q,Elemtype x){
  21. LinkNode *s;
  22. s = (LinkNode*)malloc(sizeof(LNode));
  23. s->data = x;
  24. Q.rear->next = s;
  25. Q.rear = s;
  26. }
  27. 出队:
  28. bool DeQueue (LinkQueue &Q,Elemtype e){
  29. if(Q.front==Q.rear) return false;
  30. LinkNode *p;
  31. p = Q.fornt->next;
  32. e = p->data;
  33. Q.front->next = p->next;
  34. if(p==Q.rear) Q.front=Q.rear;
  35. free(p);
  36. return true;
  37. }

数组:一种逻辑结构,是线性表的推广。

发表评论

表情:
评论列表 (有 0 条评论,39人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数据结构队列

    栈 栈是一种重要的线性结构。是我们前面讲过的线性表的一种具体形式 栈是限定仅在表尾进行插入和删除操作的线性表 由于栈本身就是一个线性表,那么我们讲的线性表的顺序存

    相关 数据结构 队列

    概述 栈和队列都是通过动态集合来存储数据,在栈和队列中添加和删除数据都是预先设定的,在栈(Stack)中,被删除的元素是最近添加的元素,所以栈的实现方式是后进先出(Las