C语言中创建空栈函数及在入栈出栈中使用的方法问询
Fixing Your Stack Implementation & Adding
createStack() Hey there! Let's break down how to add a proper createStack() function and fix some small issues in your existing code to make it more robust and modular.
First, let's address the key problems in your current code:
- You're relying on a global
toppointer andcountvariable (which isn't declared in your snippet) — this makes it impossible to create multiple independent stacks later, and globals are generally best avoided for such use cases. - In your
pushandpopfunctions, you're not correctly using thenodePtr* mytopparameter: you're assigning to the globaltopinstead of dereferencingmytopto update the caller's actual stack pointer. - There's a typo in
push:newNode->next = mytop;should benewNode->next = *mytop;sincemytopis a pointer to the top pointer.
Option 1: Simple createStack() (Using Node Pointers Directly)
If you want to stick with your original node-based approach without extra encapsulation, createStack() just needs to return an empty stack (which is a NULL pointer, since an empty stack has no nodes):
#include <stdio.h> #include <stdlib.h> typedef struct nodeRec { int item; struct nodeRec* next; } node; typedef node* nodePtr; // Create an empty stack (returns NULL, which represents an empty stack) nodePtr createStack() { return NULL; } int isempty(nodePtr mytop) { return mytop == NULL; } // Push: takes a pointer to the stack's top pointer (so we can modify it) void push(int value1, nodePtr* mytop, int* count) { node* newNode = (node*)malloc(sizeof(node)); if (newNode == NULL) { printf("\nMemory allocation failed!\n"); return; } newNode->item = value1; newNode->next = *mytop; // Point new node to current top *mytop = newNode; // Update the top pointer to the new node (*count)++; // Increment count (pass count by pointer to avoid globals) printf("\nElement added!!!\n"); } void pop(nodePtr* mytop, int* count) { if (isempty(*mytop)) { printf("\nStack is Empty!!!\n"); return; } node* temp = *mytop; // Get the current top node printf("\nDeleted element: %d", temp->item); *mytop = temp->next; // Update top to the next node free(temp); // Free the old top node (*count)--; // Decrement count } // Example usage int main() { nodePtr myStack = createStack(); // Create empty stack int stackCount = 0; push(5, &myStack, &stackCount); push(10, &myStack, &stackCount); pop(&myStack, &stackCount); pop(&myStack, &stackCount); pop(&myStack, &stackCount); // Should print "Stack is Empty!!!" return 0; }
Option 2: Encapsulated Stack (Better for Maintainability)
For a cleaner, more maintainable implementation, wrap the top pointer and count in a Stack struct. This lets you manage all stack-related data in one place, eliminating the need for globals entirely:
#include <stdio.h> #include <stdlib.h> typedef struct nodeRec { int item; struct nodeRec* next; } node; typedef node* nodePtr; // Encapsulate stack data in a struct typedef struct { nodePtr top; int count; } Stack; // Create and initialize an empty stack Stack* createStack() { Stack* stack = (Stack*)malloc(sizeof(Stack)); if (stack == NULL) { printf("\nMemory allocation failed for stack!\n"); return NULL; } stack->top = NULL; stack->count = 0; return stack; } // Free the entire stack to avoid memory leaks void destroyStack(Stack* stack) { if (stack == NULL) return; nodePtr current = stack->top; while (current != NULL) { nodePtr temp = current; current = current->next; free(temp); } free(stack); } int isempty(Stack* stack) { return stack->top == NULL; } void push(int value1, Stack* stack) { node* newNode = (node*)malloc(sizeof(node)); if (newNode == NULL) { printf("\nMemory allocation failed for new node!\n"); return; } newNode->item = value1; newNode->next = stack->top; stack->top = newNode; stack->count++; printf("\nElement added!!!\n"); } void pop(Stack* stack) { if (isempty(stack)) { printf("\nStack is Empty!!!\n"); return; } node* temp = stack->top; printf("\nDeleted element: %d", temp->item); stack->top = temp->next; free(temp); stack->count--; } // Example usage int main() { Stack* myStack = createStack(); if (myStack == NULL) return 1; push(5, myStack); push(10, myStack); pop(myStack); pop(myStack); pop(myStack); destroyStack(myStack); // Clean up memory return 0; }
Key Improvements:
- No global variables: Each stack is independent, so you can create multiple stacks if needed.
- Proper memory management: Added
destroyStack()to free all nodes and the stack struct, preventing memory leaks. - Clearer function signatures: No need to pass separate pointers for count and top — everything is encapsulated in the
Stackstruct.
内容的提问来源于stack exchange,提问作者finsters
相关产品推荐
相关产品推荐

