Search code examples
cfunctionlinked-liststackstructure

remove repeated digits and print using stack (C program)


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

struct Stack{
    int data;
    struct Stack *next;
};
 
struct Stack* newNode(int number){
     
     struct Stack *node=(struct Stack*)malloc(sizeof(struct Stack));
     node->data=number;
     node->next=NULL;
     return node;
 }
  void push(struct Stack **root_ref,int number){
      struct Stack *node=newNode(number);
      node->next=*root_ref;
      *root_ref=node;
      }
      
    int pop(struct Stack **root_ref){
        struct Stack *temp=*root_ref;
        int number=temp->data;
        *root_ref=(*root_ref)->next;
        free(temp);
        return number;
    }
    
  bool empty(struct Stack *root){
      
      return root==NULL;
  }
  
  int top(struct Stack *root){
      return root->data;
  }
 
 int main() {
    //code
    

    
    int t,num;
    scanf("%d",&t);
    while(t--){
            struct Stack *root=NULL;
        scanf("%d",&num);
           int rem=num%10;
           num=num/10;
           push(&root,rem);
        while(num!=0){
            rem=num%10;
            if(top(root)!=rem)
            push(&root,rem);
            num=num/10;
        }
       while(!empty(root)){
           printf("%d",top(root));
           pop(&root);
       } 
       
       printf("\n");
    }
    return 0;
}

For input: 1224, required output is 124, I need to remove the repeated digits and print. For test case :7777777777777777, output should be 7 but I am getting 2614897 , what is the problem, can someone tell? This is the test case where my code failed. See a few other cases:

For Input: 3 (this is number of test cases) 1233335 788777 9999

Your Output is: 1235 787 9

Why am I getting such weird output for that test case?


Solution

  • You are using the wrong data type to store num. Your integer is probably 32-bit and the maximum value in the case is +2147483647. You should consider using long or long long in order to get your tests running.

    This might be of help.