无法使用堆栈以相反的顺序显示单链表的元素?

时间:2016-11-12 09:18:18

标签: pointers singly-linked-list

我编写了程序来添加两个非常大的整数,其中每个数字都存储在链表的节点中。当我运行程序时,我的显示方法不起作用。任何人都可以告诉我我的问题是什么display()方法?

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
 int digit;
 struct node* link;
}NODE;
typedef NODE* NODEPTR;
typedef struct stack{
 int arr[100];
 int top;
}STACK;
int isEmpty(STACK* s){
 if(s->top==-1)
  return 1;
 return 0;
}
void push(STACK* s,int item){
 s->arr[++s->top]=item;
}
int pop(STACK* s){
 if(isEmpty(s))
  return -999;
 else
  return s->arr[s->top--];
}
NODEPTR insertNode(NODEPTR head,int val){
 NODEPTR curr,temp;
 temp=(NODEPTR)malloc(sizeof(NODE));
 temp->digit=val;
 temp->link=NULL;
 if(head->link==NULL)
  return temp;
 else{
  curr=head->link;
  while(curr->link!=NULL){
   curr=curr->link;
  }
  curr->link=temp;
 }
 return head;
}
NODEPTR getNumber(NODEPTR head){
 int n,i,val;
 printf("enter the number of digits in the number\n");
 scanf("%d",&n);
 for(i=1;i<=n;i++){
  printf("enter the digit at %dth position(in increasing power of   10)\n",i);
  scanf("%d",&val);
  head=insertNode(head,val);
 }
 return head;
}
NODEPTR add(NODEPTR h1,NODEPTR h2,NODEPTR h3){
 NODEPTR curr1,curr2;
 curr1=h1->link;
 curr2=h2->link;
 int carry=0,sum=0;
 while(curr1!=NULL && curr2!=NULL){
  sum=carry+curr1->digit+curr2->digit;
  if(sum>9){
   sum=sum-10;
   carry=1;
  }
  else
   carry=0;
  h3=insertNode(h3,sum);
  sum=0;
 }
 while(curr1!=NULL){
  sum=carry+curr1->digit;
  if(sum>9){
  sum=sum-10;
  carry=1;
 }
 else
  carry=0;
 h3=insertNode(h3,sum);
 sum=0;
}
while(curr2!=NULL){
 sum=carry+curr2->digit;
 if(sum>9){
  sum=sum-10;
  carry=1;
 }
else
 carry=0;
h3=insertNode(h3,sum);
sum=0;
}
return h3;
}
void display(NODEPTR head){
 STACK s;//stack to store digits of the number and then display
 s.top=-1;
 NODEPTR curr=head->link;
 while(curr!=NULL){
  push(&s,curr->digit);//pushing digits to the stack 
  curr=curr->link;
 }
 while(!isEmpty(&s))
  printf("%d",pop(&s));//poping the digits from stack so that the number appears in correct order 
}
int main(){
 NODEPTR h1,h2,h3;
 h1=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for linked list that stores the first number 
 h1->link=NULL;
 h2=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for the linked list that stores the second number 
 h2->link=NULL;
 h3=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for linked list that stores the sum of both the numbers
 h3->link=NULL;
 h1=getNumber(h1);//to get first number from user
 h2=getNumber(h2);//to get second number from user
 h3=add(h1,h2,h3);//to add both the numbers and store it in the h3 linked list
 printf("First number is:");
 display(h1);//to display the first number
 printf("second number is:");
 display(h2);//to display the second number
 printf("sum of the numbers is:");
 display(h3);//to display the sum
 return 0;
}

在运行程序时,我得到的display()方法的输出是:

第一个数字是:第二个数字是:数字之和是:

0 个答案:

没有答案