• 第10章,基本数据结构(栈,队列)


    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    typedef struct _stack{
    	int* arr;
    	int top, size;
    }stack;
    stack createStack(int size)
    {
    	stack st;
    	st.arr = (int*)malloc(size*sizeof(int));
    	st.top = -1;
    	st.size = size;
    	return st;
    }
    int isEmptyStack(stack &s)
    {
    	return s.top == -1;
    }
    void push(stack &s, int val)
    {
    	if (s.top == s.size - 1){
    		int *tmp = s.arr;
    		s.arr = (int*)malloc(2 * s.size*sizeof(int));
    		memcpy(s.arr, tmp, s.size*sizeof(int));
    		s.size = s.size * 2;
    	}
    	++s.top;
    	s.arr[s.top] = val;
    }
    int pop(stack &s)
    {
    	if (isEmptyStack(s)){
    		printf("stack is empty
    ");
    		exit(-1);
    	}
    	--s.top;
    	return s.arr[s.top + 1];
    }
    
    
    typedef struct _queue{
    	int *arr;
    	int tail, head, size;
    }queue;
    queue createQueue(int size)
    {
    	queue q;
    	q.tail = q.head = 0;
    	q.arr = (int*)malloc(size*sizeof(int));
    	q.size = size;
    	return q;
    }
    void enqueue(queue &q, int val)
    {
    	if (q.head == (q.tail + 1) % q.size){
    		int *tmp = q.arr;
    		q.arr = (int*)malloc(2 * q.size*sizeof(int));
    		memcpy(q.arr, tmp, q.size*sizeof(int));
    		q.size = 2 * q.size;
    	}
    	q.arr[q.tail] = val;
    	q.tail = (q.tail + 1) % q.size;
    }
    int dequeue(queue &q)
    {
    	if (q.tail == q.head){
    		printf("queue is empty
    ");
    		exit(-1);
    	}
    	int res = q.arr[q.head];
    	q.head = (q.head + 1) % q.size;
    	return res;
    }
    
    int main()
    {
    	int a[] = { 1, 2, 3, 4, 5, 6, 7 };
    	stack ss = createStack(5);
    	for (int i = 0; i < 7; ++i)
    		push(ss, a[i]);
    	printf("%d
    ", ss.size);
    	for (int i = 0; i < 7; ++i)
    		printf("%d	", pop(ss));
    	printf("
    ");
    
    	queue q = createQueue(5);
    	for (int i = 0; i < 5; ++i)
    		enqueue(q, a[i]);
    	dequeue(q); dequeue(q);
    	enqueue(q, 100); enqueue(q,200);
    	for (int i = 0; i <6; ++i)
    		printf("%d	", dequeue(q));
    }
    

      

  • 相关阅读:
    HDU 1882 Strange Billboard(位运算)
    Codeforces Round #243 (Div. 2) A~C
    Codeforces Round #242 (Div. 2) A~C
    2014 微软 编程之美初赛第一场 题目3 : 活动中心
    2014年微软编程之美初赛第一场 第二题 树
    POJ 2318 TOYS && POJ 2398 Toy Storage(几何)
    Coder-Strike 2014
    POJ 1269 Intersecting Lines(几何)
    HDU 1883 Phone Cell (圆覆盖最多点)
    HDU 1429 胜利大逃亡(续)(三维BFS)
  • 原文地址:https://www.cnblogs.com/jokoz/p/4696505.html
Copyright © 2020-2023  润新知