單鏈表完整模板
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* create(int val) {
Node *n = (Node*)malloc(sizeof(Node));
n->data = val; n->next = NULL;
return n;
}
void push_front(Node **head, int val) {
Node *n = create(val);
n->next = *head;
*head = n;
}
void print(Node *head) {
for (; head; head = head->next) printf("%d ", head->data);
puts("");
}
void free_list(Node *head) {
while (head) { Node *tmp = head; head = head->next; free(tmp); }
}
int main() {
Node *head = NULL;
push_front(&head, 3);
push_front(&head, 2);
push_front(&head, 1);
print(head); // 1 2 3
free_list(head);
return 0;
}
棧(順序棧)
#define MAX 100
int stack[MAX], top = -1;
void push(int x) { if (top < MAX-1) stack[++top] = x; }
int pop() { return (top >= 0) ? stack[top--] : -1; }
隊列(循環隊列)
#define MAX 100
int queue[MAX], front = 0, rear = 0;
void enqueue(int x) { if ((rear+1)%MAX != front) queue[rear] = x, rear = (rear+1)%MAX; }
int dequeue() { if (front != rear) { int x = queue[front]; front = (front+1)%MAX; return x; } return -1; }
二叉樹(鏈式存儲)
typedef struct TreeNode {
int data;
struct TreeNode *left, *right;
} TreeNode;
TreeNode* new_node(int val) {
TreeNode *n = malloc(sizeof(TreeNode));
n->data = val; n->left = n->right = NULL;
return n;
}
void preorder(TreeNode *root) {
if (root) { printf("%d ", root->data); preorder(root->left); preorder(root->right); }
}
學習建議