该程序具有push,pop和rotate功能。 rotate函数被认为是堆栈中的前三项
如果堆栈中的数字是:
2
6
5
8
9
在您调用rotate
函数后,它们应该是:
5
2
6
8
9
推送和弹出功能是正确的,我只是不确定如何正确实现这个旋转功能
#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");
}
答案 0 :(得分:1)
使用您已有的代码
int v1,v2,v3;
pop(stack, &v1);
pop(stack, &v2);
pop(stack, &v3);
push(stack, v3);
push(stack, v1);
push(stack, v2);