数据结构:栈、队列(顺序存储结构)-C&Java实现

栈(顺序存储结构)

Stack.c

/**
 * 数据结构:
 * 栈的存储结构定义和其基本方法
 * 
 * @author TagBug
 * @date 2021.09.22 08:10:08
 */
#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
#define INCREMENT_SIZE 10

typedef unsigned short Bool;
typedef int Elemtype;

/**
 * base为数组
 * top为栈顶指针,指向栈顶下一位置,当top=0时表示栈空
 * stackSize为目前栈大小
 */
typedef struct
{
    Elemtype *base;
    int top;
    int stackSize;
} Stack;

/**
 * 将元素入栈,并在必要时给其扩容
 * 
 * @param stack 栈
 * @param elem 欲推入的元素
 */
Bool push(Stack *stack, Elemtype elem)
{
    // 如果栈顶指针大于栈大小,先将栈扩容
    if (stack->top > stack->stackSize)
    {
        Elemtype *newBase = (Elemtype *)realloc(stack->base, sizeof(Elemtype) * (stack->stackSize + INCREMENT_SIZE));
        if (!newBase)
        {
            printf("重新分配内存失败!\n");
            return FALSE;
        }
        stack->base = newBase;
    }
    // 推入元素
    stack->base[stack->top] = elem;
    stack->top += 1;
    return TRUE;
}

/**
 * 将元素出栈
 * 
 * @param stack 栈
 * @param elem 用于存放获取的元素
 */
Bool pop(Stack *stack, Elemtype *elem)
{
    // 如果栈为空
    if (stack->top == 0)
    {
        printf("栈为空!");
        return FALSE;
    }
    stack->top -= 1;
    // 指针有效才赋值
    if (elem)
    {
        *elem = stack->base[stack->top];
    }
    return TRUE;
}

/**
 * 创建一个空栈
 * 
 * @return 栈指针或NULL(当内存分配失败时)
 */
Stack *createStack()
{
    Stack *stack = (Stack *)calloc(1, sizeof(Stack));
    if (!stack)
    {
        printf("内存分配失败!");
        return NULL;
    }
    Elemtype *newBase = (Elemtype *)malloc(sizeof(Elemtype) * STACK_INIT_SIZE);
    if (!newBase)
    {
        printf("内存分配失败!");
        free(stack);
        return NULL;
    }
    stack->base = newBase;
    stack->stackSize = STACK_INIT_SIZE;
    return stack;
}

/**
 * 按序打印出栈
 */
void display(Stack *stack)
{
    printf("Stack[@%x]:\n", stack);
    if (stack->top == 0)
    {
        printf("[-空表-]\n");
        return;
    }
    for (int i = 0; i < stack->top; i++)
    {
        if (i > 0)
        {
            printf("-> ");
        }
        printf("%d ", stack->base[i]);
    }
    printf("\n");
}

// Test
int main(int argc, char const *argv[])
{
    int data[] = {5, 12, 45, 32, 1111, 33, 23, 455, 9, 0};
    Stack *stack = createStack();
    for (int i = 0; i < 10; i++)
    {
        push(stack, data[i]);
    }
    display(stack); // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455 -> 9 -> 0
    pop(stack, NULL);
    pop(stack, NULL);
    display(stack); // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455
    return 0;
}

DataStruct/Stack.java

package DataStruct;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 数据结构: 栈的存储结构定义和其基本方法
 * 
 * @param base      数组
 * @param top       栈顶指针,指向栈顶下一位置,当top=0时表示栈空
 * @param stackSize 目前栈大小
 * @author TagBug
 * @date 2021.09.22 08:10:08
 */
public class Stack<T> {
    private static final int STACK_INIT_SIZE = 100;
    private static final int INCREMENT_SIZE = 10;

    private T[] base;
    private int top;
    private int size;

    /**
     * 创建一个空栈
     * 
     * @param type 栈元素类型
     */
    @SuppressWarnings("unchecked")
    public Stack(Class<T> type) {
        base = (T[]) Array.newInstance(type, STACK_INIT_SIZE);
        top = 0;
        size = STACK_INIT_SIZE;
    }

    /**
     * 将元素入栈,并在必要时给其扩容
     * 
     * @param elem 欲推入的元素
     */
    public void push(T elem) {
        // 如果栈满则扩容
        if (top > size) {
            base = Arrays.copyOf(base, size + INCREMENT_SIZE);
        }
        // 推入元素
        base[top] = elem;
        top += 1;
    }

    /**
     * 将元素出栈
     * 
     * @param elem 用于存放获取的元素
     */
    public T pop() {
        // 如果栈空
        if (top <= 0) {
            throw new IllegalStateException("栈为空!");
        }
        top -= 1;
        return base[top];
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());
        sb.append(":\n");
        if (top == 0) {
            sb.append("[-空表-]");
            return sb.toString();
        }
        for (int i = 0; i < top; i++) {
            if (i > 0) {
                sb.append("-> ");
            }
            sb.append(base[i]);
            sb.append(' ');
        }
        return sb.toString();
    }

    /**
     * 测试用例
     * 
     * @param args
     */
    public static void main(String[] args) {
        Integer[] data = { 5, 12, 45, 32, 1111, 33, 23, 455, 9, 0 };
        Stack<Integer> stack = new Stack<>(Integer.class);
        System.out.println(stack); // [空表]
        for (Integer n : data) {
            stack.push(n);
        }
        System.out.println(stack); // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455 -> 9 -> 0
        stack.pop();
        stack.pop();
        System.out.println(stack); // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455
    }
}

队列(顺序存储结构)

Queue.c

/**
 * 数据结构:
 * 队列的存储结构定义和其基本方法
 * 
 * @author TagBug
 * @date 2021.09.22 09:23:21
 */
#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0
#define MAX_SIZE 100

typedef unsigned short Bool;
typedef int Elemtype;

/**
 * data为数组
 * front为队首指针,指向队首元素
 * rear为队尾指针,指向队尾元素
 * 当front==rear时,表示队列为空
 * 当(rear+1)%queueSize==front时,表示队列为满
 * queueSize为目前实际队列大小
 * 队列可用空间永远比queueSize少1(留下一个空位用于判断队列为满)
 */
typedef struct
{
    Elemtype *data;
    int front;
    int rear;
    int queueSize;
} Queue;

/**
 * 返回队列大小
 */
int getLength(Queue *queue)
{
    if ((queue->rear + 1) % queue->queueSize == queue->front)
    {
        return 0;
    }
    if (queue->front <= queue->rear)
    {
        return queue->rear - queue->front + 1;
    }
    else
    {
        return queue->rear + queue->queueSize - queue->front + 1;
    }
}

/**
 * 将元素添加到队首
 */
Bool addFirst(Queue *queue, Elemtype elem)
{
    if ((queue->rear + 1) % queue->queueSize == queue->queueSize)
    {
        printf("队列已满!");
        return FALSE;
    }
    int idx = queue->front - 1;
    queue->front = idx < 0 ? queue->queueSize - 1 : idx;
    queue->data[queue->front] = elem;
    return TRUE;
}

/**
 * 将元素添加到队尾
 */
Bool addLast(Queue *queue, Elemtype elem)
{
    if ((queue->rear + 1) % queue->queueSize == queue->queueSize)
    {
        printf("队列已满!");
        return FALSE;
    }
    int idx = (queue->rear + 1) % queue->queueSize;
    queue->rear = idx;
    queue->data[idx] = elem;
    return TRUE;
}

/**
 * 将元素从队首移除
 */
Bool removeFirst(Queue *queue, Elemtype *elem)
{
    if (getLength(queue) == 0)
    {
        printf("队列为空!");
        return FALSE;
    }
    if (elem)
    {
        *elem = queue->data[queue->front];
    }
    queue->front = (queue->front + 1) % queue->queueSize;
    return TRUE;
}

/**
 * 将元素从队尾移除
 */
Bool removeLast(Queue *queue, Elemtype *elem)
{
    if (getLength(queue) == 0)
    {
        printf("队列为空!");
        return FALSE;
    }
    if (elem)
    {
        *elem = queue->data[queue->rear];
    }
    int idx = queue->rear - 1;
    queue->rear = idx < 0 ? queue->queueSize - 1 : idx;
    return TRUE;
}

/**
 * 创建一个空队列
 * 
 * @return 栈指针或NULL(当内存分配失败时)
 */
Queue *createQueue()
{
    Queue *queue = (Queue *)calloc(1, sizeof(Queue));
    if (!queue)
    {
        printf("内存分配失败!");
        return NULL;
    }
    Elemtype *newData = (Elemtype *)malloc(sizeof(Elemtype) * MAX_SIZE);
    if (!newData)
    {
        printf("内存分配失败!");
        free(queue);
        return NULL;
    }
    queue->data = newData;
    queue->queueSize = MAX_SIZE;
    queue->front = 0;
    queue->rear = -1;
    return queue;
}

/**
 * 按序打印出队列
 */
void display(Queue *queue)
{
    printf("Stack[@%x]:\n", queue);
    if (getLength(queue) == 0)
    {
        printf("[-空表-]\n");
        return;
    }
    if (queue->front < queue->rear)
    {
        for (int i = queue->front; i <= queue->rear; i++)
        {
            if (i > queue->front)
            {
                printf("-> ");
            }
            printf("%d ", queue->data[i]);
        }
    }
    else
    {
        for (int i = queue->front; i < queue->queueSize; i++)
        {
            if (i > queue->front)
            {
                printf("-> ");
            }
            printf("%d ", queue->data[i]);
        }
        for (int i = 0; i <= queue->rear; i++)
        {
            printf("-> ");
            printf("%d ", queue->data[i]);
        }
    }
    printf("\n");
}

// Test
int main(int argc, char const *argv[])
{
    int dataFront[] = {1111, 32, 45, 12, 5};
    int dataRear[] = {33, 23, 455, 9, 0};
    Queue *queue = createQueue();
    for (int i = 0; i < 5; i++)
    {
        addFirst(queue, dataFront[i]);
    }
    for (int i = 0; i < 5; i++)
    {
        addLast(queue, dataRear[i]);
    }
    printf("%d\n", getLength(queue)); // 10
    display(queue);                   // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455 -> 9 -> 0
    removeFirst(queue, NULL);
    removeLast(queue, NULL);
    printf("%d\n", getLength(queue)); // 8
    display(queue);                   // 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455 -> 9
    return 0;
}

DataStruct/Queue.java

package DataStruct;

import java.lang.reflect.Array;

/**
 * 数据结构: 栈的存储结构定义和其基本方法
 * 
 * @param data      数组
 * @param front     队首指针,指向队首元素
 * @param rear      队尾指针,指向队尾元素<br>
 *                  当front==rear时,表示队列为空<br>
 *                  当(rear+1)%queueSize==front时,表示队列为满
 * @param queueSize 目前实际队列大小<br>
 *                  队列可用空间永远比queueSize少1(留下一个空位用于判断队列为满)
 * @author TagBug
 * @date 2021.09.22 08:10:08
 */
public class Queue<T> {
    private static final int QUEUE_INIT_SIZE = 100;
    // private static final int INCREMENT_SIZE = 10;

    private T[] data;
    private int front;
    private int rear;
    private int queueSize;

    /**
     * 创建一个空队列
     * 
     * @param type 队列元素类型
     */
    @SuppressWarnings("unchecked")
    public Queue(Class<T> type) {
        data = (T[]) Array.newInstance(type, QUEUE_INIT_SIZE);
        front = 0;
        rear = -1;
        queueSize = QUEUE_INIT_SIZE;
    }

    /**
     * 将元素添加到队首
     */
    public boolean addFirst(T elem) {
        if ((rear + 1) % queueSize == queueSize) {
            System.out.println("队列已满!");
            return false;
        }
        int idx = front - 1;
        front = idx < 0 ? queueSize - 1 : idx;
        data[front] = elem;
        return true;
    }

    /**
     * 将元素添加到队尾
     */
    public boolean addLast(T elem) {
        if ((rear + 1) % queueSize == queueSize) {
            System.out.println("队列已满!");
            return false;
        }
        int idx = (rear + 1) % queueSize;
        rear = idx;
        data[idx] = elem;
        return true;
    }

    /**
     * 将元素从队首移除
     */
    public T removeFirst() {
        if (getLength() == 0) {
            throw new IllegalStateException("队列为空!");
        }
        T elem = data[front];
        front = (front + 1) % queueSize;
        return elem;
    }

    /**
     * 将元素从队尾移除
     */
    public T removeLast() {
        if (getLength() == 0) {
            throw new IllegalStateException("队列为空!");
        }
        T elem = data[rear];
        int idx = rear - 1;
        rear = idx < 0 ? queueSize - 1 : idx;
        return elem;
    }

    /**
     * 返回队列大小
     */
    int getLength() {
        if ((rear + 1) % queueSize == front) {
            return 0;
        }
        if (front <= rear) {
            return rear - front + 1;
        } else {
            return rear + queueSize - front + 1;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());
        sb.append(":\n");
        if (getLength() == 0) {
            sb.append("[-空表-]");
            return sb.toString();
        }
        if (front <= rear) {
            for (int i = front; i <= rear; i++) {
                if (i > front) {
                    sb.append("-> ");
                }
                sb.append(data[i]);
                sb.append(' ');
            }
        } else {
            for (int i = front; i < queueSize; i++) {
                if (i > front) {
                    sb.append("-> ");
                }
                sb.append(data[i]);
                sb.append(' ');
            }
            for (int i = 0; i <= rear; i++) {
                sb.append("-> ");
                sb.append(data[i]);
                sb.append(' ');
            }
        }
        return sb.toString();
    }

    /**
     * 测试用例
     * 
     * @param args
     */
    public static void main(String[] args) {
        Integer[] dataFront = { 1111, 32, 45, 12, 5 };
        Integer[] dataRear = { 33, 23, 455, 9, 0 };
        Queue<Integer> queue = new Queue<>(Integer.class);
        for (Integer n : dataFront) {
            queue.addFirst(n);
        }
        for (Integer n : dataRear) {
            queue.addLast(n);
        }
        System.out.println(queue.getLength()); // 10
        System.out.println(queue); // 5 -> 12 -> 45 -> 32 -> 1111 -> 33 -> 23 -> 455 -> 9 -> 0
        queue.removeFirst();
        queue.removeLast();
        System.out.println(queue); // 12 -> 45 -> 1111 -> 33 -> 455 -> 9
        System.out.println(queue.getLength()); // 8
        queue.removeFirst();
        queue.removeFirst();
        queue.removeFirst();
        queue.removeFirst();
        queue.removeFirst();
        queue.removeFirst();
        System.out.println(queue.getLength()); // 2
        queue.removeLast();
        queue.removeLast();
        System.out.println(queue.getLength()); // 0
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值