首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

數據結構 C 語言實現:鏈表/棧/隊列/樹 核心代碼模板

     編輯:程式設計疑難解答

單鏈表完整模板

#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); }
}

學習建議

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved