首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

去掉重复的数字并使用堆栈打印(C程序)

去掉重复的数字并使用堆栈打印是一个常见的编程问题,可以通过使用堆栈数据结构来解决。下面是一个C程序的示例代码:

代码语言:txt
复制
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define STACK_SIZE 100

typedef struct {
    int data[STACK_SIZE];
    int top;
} Stack;

void initStack(Stack* stack) {
    stack->top = -1;
}

bool isStackEmpty(Stack* stack) {
    return stack->top == -1;
}

bool isStackFull(Stack* stack) {
    return stack->top == STACK_SIZE - 1;
}

void push(Stack* stack, int value) {
    if (isStackFull(stack)) {
        printf("Stack is full. Cannot push element.\n");
        return;
    }
    stack->data[++stack->top] = value;
}

int pop(Stack* stack) {
    if (isStackEmpty(stack)) {
        printf("Stack is empty. Cannot pop element.\n");
        return -1;
    }
    return stack->data[stack->top--];
}

void removeDuplicatesAndPrint(int* nums, int size) {
    Stack stack;
    initStack(&stack);

    for (int i = 0; i < size; i++) {
        if (isStackEmpty(&stack) || nums[i] != stack.data[stack.top]) {
            push(&stack, nums[i]);
        }
    }

    printf("Result: ");
    while (!isStackEmpty(&stack)) {
        printf("%d ", pop(&stack));
    }
    printf("\n");
}

int main() {
    int nums[] = {1, 2, 2, 3, 4, 4, 5};
    int size = sizeof(nums) / sizeof(nums[0]);

    removeDuplicatesAndPrint(nums, size);

    return 0;
}

这段代码实现了去除重复数字并使用堆栈打印的功能。它使用了一个自定义的堆栈数据结构,并定义了一些常用的堆栈操作函数。在removeDuplicatesAndPrint函数中,遍历输入数组,如果堆栈为空或当前数字不等于堆栈顶部的数字,则将当前数字压入堆栈。最后,依次弹出堆栈中的元素并打印出来,即可得到去重后的结果。

这个问题的应用场景可以是需要对一组数字进行去重操作,并按照特定顺序输出结果的场景。例如,对于一个用户输入的数字序列,我们可以使用这个算法去除重复数字,并按照用户输入的顺序打印出来。

推荐的腾讯云相关产品和产品介绍链接地址:

  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 腾讯云云原生容器服务(TKE):https://cloud.tencent.com/product/tke
  • 腾讯云人工智能平台(AI Lab):https://cloud.tencent.com/product/ai
  • 腾讯云物联网平台(IoT Hub):https://cloud.tencent.com/product/iothub
  • 腾讯云移动开发平台(MTP):https://cloud.tencent.com/product/mtp
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云区块链服务(BCS):https://cloud.tencent.com/product/bcs
  • 腾讯云元宇宙平台(Tencent Real-Time Rendering (TRTR)):https://cloud.tencent.com/product/trtr
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分38秒

一套电商系统是怎么开发出来的?

领券