在C语言编程中,栈是一种非常重要的数据结构,广泛应用于算法设计中。正确使用栈可以提升代码的深度与效率。本文将深入探讨C语言编程中的栈技巧,帮助你更好地理解和运用栈。一、栈的基本概念栈是一种后进先出(L...
在C语言编程中,栈是一种非常重要的数据结构,广泛应用于算法设计中。正确使用栈可以提升代码的深度与效率。本文将深入探讨C语言编程中的栈技巧,帮助你更好地理解和运用栈。
栈是一种后进先出(LIFO)的数据结构,它只允许在一端进行插入和删除操作。栈通常用数组或链表实现。
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int value) { if (top < MAX_SIZE - 1) { stack[++top] = value; }
}
int pop() { if (top >= 0) { return stack[top--]; } return -1; // 栈为空时返回-1
}typedef struct Node { int data; struct Node* next;
} Node;
Node* createStack() { Node* head = NULL; return head;
}
void push(Node* head, int value) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = value; newNode->next = head; head = newNode;
}
int pop(Node* head) { if (head == NULL) { return -1; // 栈为空时返回-1 } int value = head->data; Node* temp = head; head = head->next; free(temp); return value;
}#define MAX_EXPR_LEN 100
void infixToPostfix(char* infix, char* postfix) { int len = strlen(infix); int top = -1; char stack[MAX_EXPR_LEN]; for (int i = 0; i < len; i++) { if (infix[i] >= '0' && infix[i] <= '9') { postfix[top + 1] = infix[i]; top++; } else if (infix[i] == '(') { stack[++top] = infix[i]; } else if (infix[i] == ')') { while (stack[top] != '(') { postfix[top + 1] = stack[top--]; } top--; } else { while (top >= 0 && getPrecedence(stack[top]) >= getPrecedence(infix[i])) { postfix[top + 1] = stack[top--]; } stack[++top] = infix[i]; } } while (top >= 0) { postfix[top + 1] = stack[top--]; } postfix[top + 2] = '\0';
}
int getPrecedence(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; }
}int evaluatePostfix(char* postfix) { int len = strlen(postfix); int top = -1; int stack[MAX_EXPR_LEN]; for (int i = 0; i < len; i++) { if (postfix[i] >= '0' && postfix[i] <= '9') { stack[++top] = postfix[i] - '0'; } else { int val2 = stack[top--]; int val1 = stack[top--]; switch (postfix[i]) { case '+': stack[++top] = val1 + val2; break; case '-': stack[++top] = val1 - val2; break; case '*': stack[++top] = val1 * val2; break; case '/': stack[++top] = val1 / val2; break; } } } return stack[top];
}通过以上介绍,相信你已经对C语言编程中的栈有了更深入的了解。熟练运用栈可以提升你的代码深度与效率。在实际编程中,可以根据需求选择合适的栈实现方式,并灵活运用拓栈技巧。