使用堆栈添加 2 个大数?

Adding 2 large numbers using stack?

我目前正在学习 C 编程语言(这也是我的第一门编程语言)。我现在正在处理使用堆栈添加 2 个大数的问题。我已经编写了一些代码来解决它,但我遇到了一些错误。

这是我的代码。

主程序

#include "stack.h"
#include <string.h>

int main(){
  node *top1,*top2,*top3;
  int i=0,n1,n2,flag=0,adder;
  char number1[50],number2[50];
  printf("Enter the first number: ");
  scanf(" %s",number1);
  printf("Enter the second number: ");
  scanf(" %s",number2);
  n1 = strlen(number1);
  n2 = strlen(number2);

  while (i<=n1 || i<=n2){
    push(top1,(number1[i]-'0'));
    push(top2,(number2[i]-'0'));
    i++;
  }

  while(!isEmpty(top1) || !isEmpty(top2)){
    adder = pop(top1) + pop(top2) + flag;
    if (adder >= 10) {
      push(top3,adder-10);
      flag = 1;
    } else {
      push(top3,adder);
      flag=0;
    }
  }
  printf("The result is: ");
  while (!isEmpty(top3)){
    printf("%d",pop(top3));
  }
  printf("\n");
  return 0;
}

stack.h 库

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct node_t {
  ElementType data;
  struct node_t *next;
}node;

int isEmpty(node *top){
  return (top==NULL);
}

void push(node *top,ElementType value){
  node *p;
  p = (node*)malloc(sizeof(node));
  if (p==NULL) {
    printf("Allocation failed!\n");
    exit(0);
  }
  p->data = value;
  p->next=top;
  top = p;
}

ElementType pop(node *top){
  if (isEmpty(top)){
    printf("The stack is empty!\n");
    return 0;
  } else {
  node *p;
  ElementType value;
  value = top->data;
  p = top;
  top = top->next;
  free(p);
  return value;
  }
}

编译完成,但当我输入2个数字时,出现核心转储错误。我尝试使用 gdb 进行查找,结果如下。

#0  0x00007ffff7a44267 in __GI_raise (sig=sig@entry=6)
    at ../sysdeps/unix/sysv/linux/raise.c:55
#1  0x00007ffff7a45eca in __GI_abort () at abort.c:89
#2  0x00007ffff7a87c53 in __libc_message (do_abort=do_abort@entry=1, 
    fmt=fmt@entry=0x7ffff7ba01a8 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff7a939f8 in malloc_printerr (ptr=<optimized out>, 
    str=0x7ffff7ba01d0 "munmap_chunk(): invalid pointer", 
    action=<optimized out>) at malloc.c:4965
#4  munmap_chunk (p=<optimized out>) at malloc.c:2820
#5  __GI___libc_free (mem=<optimized out>) at malloc.c:2945
#6  0x000000000040083c in push (top=0x7fffffffe201, value=1) at stack.h:24
#7  0x0000000000400955 in main () at teststack1.c:16
(gdb) 

分段错误可能是由于您在 push 函数中释放 top 造成的。你真的不想这样做,因为调用代码正在使用它。但是该程序还有其他一些缺陷。例如:
代码中的逻辑错误:

while(!isEmpty(top1) || !isEmpty(top2)){
    adder = pop(top1) + pop(top2) + flag;
.....

条件为真,而 top1top2 非空。意思是其中一个可以为空。但是你试图从他们两个中 pop ,甚至是空的。