lodam
lodam

Reputation: 77

Stack push pop rotate

This program has the functions push, pop and rotate. The rotate function is supposed the top three items on the stack

If the numbers in the stack are:

2
6
5
8
9

After you call the rotate function they should be:

5
2
6
8
9

The push and pop functions are correct, i'm just not sure how to implement this rotate function correctly

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

struct node* push(struct node* top, int i) {
   struct node *new_node;
   new_node = malloc(sizeof(struct node));
   if(new_node == NULL) {
    printf("malloc failed");
        return top;
   }

   new_node->value = i;
   new_node->next = top;
   return new_node;

}

struct node *make_empty(struct node *top) {
   return NULL;
}

struct node *pop(struct node *top, int *i) {
   struct node *new_node;
   new_node = malloc(sizeof(struct node));
   if (new_node == NULL) {
    printf("malloc failed");
    return top;
   } 

   *i = top->value;
   new_node = top;
   top = top->next;
   free(new_node);
   return top;
}

struct node *rotate(struct node *top) {

   struct node *new_node;
   struct node *prev = top;
   struct node *cur = top;
   int i;

   new_node = malloc(sizeof(struct node));
   if (new_node == NULL) {
    printf("malloc failed");
    return top;
   }

  i = cur->value;
   top = top->next;

   new_node->next = top->next;
   new_node->value = cur->value;

   return new_node;
} 
void print_stack(struct node *top) {
   struct node *p;
   if(top != NULL) {
      for(p = top; p !=NULL; p=p->next)
    printf("%d\n", p->value);
      printf("\n");
   }
   else
      printf("stack is empty\n");
}

Upvotes: 0

Views: 1521

Answers (1)

pm100
pm100

Reputation: 50190

use the code you already have

int v1,v2,v3;
pop(stack, &v1);
pop(stack, &v2);
pop(stack, &v3);
push(stack, v3);
push(stack, v1);
push(stack, v2);

Upvotes: 1

Related Questions