Question

So I'm supposed to right a method in c that moves all negative numbers in a stack on top. My plan to do this was to separate the negatives and positives into 2 different stacks and then merge them afterwards.

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

#define SIZEMAX 10

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

typedef struct stack
    {
    node *head;
    int stksize;
    }stack;

void initialize(stack *stk)
   {
   stk->head=NULL;
   stk->stksize=0;
   }

void push(stack *stk,int x)
   {
   if (stk->stksize==SIZEMAX)
      {  
      printf("stack full");
      return;
      }

   node *temp=(node*)malloc(sizeof(node));
   temp->data=x;
   temp->next=stk->head;
   stk->head=temp;
   stk->stksize++;
   }

void print(stack *stk)
   {
   node *temp=stk->head;
   while(temp!=NULL)
      {
      printf("|%d|\n",temp->data);
      temp=temp->next;
      }
   }

void pop(stack *stk)
   {
   node *temp=(node*)malloc(sizeof(node));
   if (stk->stksize==0)
      {
      printf("nothing to pop");
      return;
      }

   temp->data=stk->head->data;
   temp=stk->head->next;
   stk->head=temp;
   free(temp);
   stk->stksize--;
   }

void partition(stack *stk)
   {
   stack negative,positive;

   initialize(&negative);
   initialize(&positive);
   while (stk->stksize!=0)
      {
      if (stk->head->data<0)
         {   
         push(&negative,stk->head->data);
         pop(stk);
         }
      if (stk->head->data>0)
         {
         push(&positive,stk->head->data);
         pop(stk);
         }
      }
   }

int main()
   {
   int i,x;
   stack mystk;
   initialize(&mystk);

   for(i=0;i<5;i++)
      {
      scanf("%d",&x);
      push(&mystk,x);
      }

   print(&mystk);
   partition(&mystk);
   printf("\n");
   print(&mystk);

   return(0);
   } 

After calling the partition function in the main I should get nothing because everything in the stack was popped but instead i get never ending chain of numbers. I can't figure out the problem.

Was it helpful?

Solution

Your issue lies in the pop() function. It should look like

void pop(stack *stk)
{
   if (stk->stksize==0)
   {
      printf("nothing to pop");
      return;
   }

   node *temp=stk->head->next;
   free(stk->head);
   stk->head = temp;
   stk->stksize--;
}

Live demo

And don't forget to handle the 0 in your partition() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top