5 4 dataM Push Pop Push S S

  • Slides: 30
Download presentation

顺序栈 5 4 – 实现:一维数组data[M] 栈顶指针并不一定是 指针变量,也可以是 下标变量 假设:调用两次Push函数 假设:调用一次Pop函数 Push( S, S); ‘A’);

顺序栈 5 4 – 实现:一维数组data[M] 栈顶指针并不一定是 指针变量,也可以是 下标变量 假设:调用两次Push函数 假设:调用一次Pop函数 Push( S, S); ‘A’); #define SIZE 50 Pop( 2 top=2 Push(S, ’B’); typedef struct B 1 top=1 /* 进栈*/ /* 出栈*/ { A 0 char Pop(Seq. Stack *S) top=0 void Push(Seq. Stack *S,char x) char data[SIZE]; 栈空 {{ int top; if(Stack. Empty(S)) if (Stack. Full(S)) }Seq. Stack; { printf(“Stack underflow”); //下溢,退出运行 { printf(“Stack overflow”); //上溢,退出运行 exit(0); } exit(0) ; } /*置栈空*/ return S->data[--S->top]; S->data[S->top++]=x; //将x入栈, 栈顶指针加 1 void Init. Stack(Seq. Stack *S) //将栈顶指针减 1后, } { S->top=0; 栈顶元素返回 } } 3

void Init. Queue(struct queue *q) { //初始化队列 struct queue. Node * node; node=(struct queue.

void Init. Queue(struct queue *q) { //初始化队列 struct queue. Node * node; node=(struct queue. Node *)malloc(sizeof(struct queue. Node )); node->next=NULL; q->front=node; q->rear=node; } node q. front q. rear 带头结点的空队列 ^

//入队列 void Add. Queue(struct queue * q, int e) { struct queue. Node *

//入队列 void Add. Queue(struct queue * q, int e) { struct queue. Node * node; node=(struct queue. Node *)malloc(sizeof(struct queue. Node )); node->data=e; node->next=NULL; q->rear->next=node; q->rear=node; } node q. front q. rear ^ 1 ^ 又调用一次

//入队列 void Add. Queue(struct queue * q, int e) { struct queue. Node *

//入队列 void Add. Queue(struct queue * q, int e) { struct queue. Node * node; node=(struct queue. Node *)malloc(sizeof(struct queue. Node )); node->data=e; node->next=NULL; q->rear->next=node; q->rear=node; } node q. front q. rear 1 ^ 2 ^ 又调用一次

//出队 int Del. Queue (struct Queue *q) { int x; struct Queue. Node *p;

//出队 int Del. Queue (struct Queue *q) { int x; struct Queue. Node *p; p=q->front->next; q->front->next=p->next; if(p->next==NULL) q->rear=q->front; // 防止尾指针丢失 x=p->data; if不成立 free(p); return x; } p q. front 1 2 ^ x 1 q. rear 又调用一次

//出队 int Del. Queue (struct Queue *q) { int x; struct Queue. Node *p;

//出队 int Del. Queue (struct Queue *q) { int x; struct Queue. Node *p; p=q->front->next; q->front->next=p->next; if(p->next==NULL) q->rear=q->front; // 防止尾指针丢失 x=p->data; if成立 free(p); return x; } p q. front ^ 2 ^ x 12 q. rear 又调用一次

r ea Q. r 入队 ar e r. Q ont r f. Q 4

r ea Q. r 入队 ar e r. Q ont r f. Q 4 Q. front→ 2 B 1 A 0 出队 对应为: Q. r D C Q. rear 0 3 2 ear Q. r nt ea r Q. front→ C A 4 fro Q. front→ 3 Q. D 1 B QQ. . rea fro r nt

nt 4 D 3 2 G 1 F 0 ar e r. Q ront

nt 4 D 3 2 G 1 F 0 ar e r. Q ront Q. f E 对应为: Q. rear 4 D nt o r f. Q C Q. rear 队空:Q. rear=Q. front Q. rear 出队 继续入队 考虑出队 情况 0 3 2 Q. f ront ron t Q. front→ 但是 fro E C Q. 入队 队满:Q. rear=Q. front F 1 G QQ. re. fr ar on t 因此,一般循环队列少用一个 存储空间; 队满条件就变为: (Q. rear+1)%M==Q. front

E E 4 D 0 3 2 1 F 4 D F 1 C

E E 4 D 0 3 2 1 F 4 D F 1 C fro nt Q. fro Q. rear nt C Q. 3 2 G 0 队满 rea r