Untitled
unknown
plain_text
a year ago
2.4 kB
0
Indexable
Never
#include <stdio.h> #include <stdlib.h> #define MAX_ACTIONS 100 typedef struct { char* action; } Action; typedef struct { Action* actions[MAX_ACTIONS]; int top; } UndoRedoStack; UndoRedoStack undoStack, redoStack; void push(UndoRedoStack* stack, Action* action) { if (stack->top < MAX_ACTIONS - 1) { stack->actions[++stack->top] = action; } else { printf("Stack is full. Cannot push more actions.\n"); } } Action* pop(UndoRedoStack* stack) { if (stack->top >= 0) { return stack->actions[stack->top--]; } else { printf("Stack is empty.\n"); return NULL; } } void performAction(char* actionString) { Action* action = (Action*)malloc(sizeof(Action)); action->action = actionString; push(&undoStack, action); printf("Performed action: %s\n", actionString); // Clear redo stack when a new action is performed while (redoStack.top >= 0) { free(pop(&redoStack)); } } void undo() { Action* action = pop(&undoStack); if (action != NULL) { printf("Undo: %s\n", action->action); push(&redoStack, action); } } void redo() { Action* action = pop(&redoStack); if (action != NULL) { printf("Redo: %s\n", action->action); push(&undoStack, action); } } int main() { undoStack.top = -1; redoStack.top = -1; while (1) { printf("Enter a command (perform/undo/redo/quit): "); char command[50]; fgets(command, sizeof(command), stdin); if (strcmp(command, "perform\n") == 0) { printf("Enter the action to perform: "); char actionString[50]; fgets(actionString, sizeof(actionString), stdin); performAction(actionString); } else if (strcmp(command, "undo\n") == 0) { undo(); } else if (strcmp(command, "redo\n") == 0) { redo(); } else if (strcmp(command, "quit\n") == 0) { break; } else { printf("Invalid command. Please try again.\n"); } } // Free memory for remaining actions while (undoStack.top >= 0) { free(pop(&undoStack)); } while (redoStack.top >= 0) { free(pop(&redoStack)); } return 0; }