[] Data structure to create a single linked list, doubly linked list, binary tree (C ++ complete code)

Create a single list of

Creating a single linked list: 1-> 2-> 3-> 4-> NULL (tail interpolation)

#include <iostream>

using namespace std;

struct ListNode {
    int data;
    ListNode *next;
    ListNode(int x): data(x), next(NULL) {}
};

int main() {
    // Create a single linked list 1->2->3->4->NULL 1->2->3->4->NULL
    ListNode *head = new ListNode(-1);
    ListNode *a = head;
    for (int i = 1; i <= 4; i ++) {
        ListNode *b = new ListNode(i);
        // 尾插法
        a->next = b;
        a = b;
    }
    a->next = NULL;

    // 遍历输出链表
    ListNode *p = head->next;
    while(p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    puts("");

    return 0;
}

Create a doubly-linked list

#include <iostream>

using namespace std;

struct ListNode {
    int data;
    ListNode *prior;
    ListNode *next;
    ListNode(int x)
        : data(x)
        , next(NULL) {
    }
};

int main() {
    // create a double linked list 1->2->3->4->NULL
    ListNode *head = new ListNode(-1);
    ListNode *a = head;
    for (int i = 1; i <= 4; i++) {
        ListNode *b = new ListNode(i);
        // 尾插法
        a->next = b;
        b->prior = a; // The only difference  with single list
        a = b;
    }

    a->next = NULL;

    // 顺序遍历链表
    ListNode *p = head->next;
    while (p->next != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("%d ", p->data);
    puts("");
    // 输出1 2 3 4

    // 逆序遍历链表
    while (p != head) {
        printf("%d ", p->data);
        p = p->prior;
    }
    puts("");
    // 输出 4 3 2 1

    return 0;
}

Create a binary tree

#include <iostream>
using namespace std;

// 定义二叉树结点
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x)
        : val(x)
        , left(NULL)
        , right(NULL) {
    }
};

// 核心:构建一棵二叉树 input数据必须是二叉树前序遍历结果,用-1表示空结点
/*
tree:
       3
    5    -1
 -1  -1
input:
3 5 -1 -1 -1
*/
TreeNode *buildTree() {
    int d;
    cin >> d;
    if (d == -1) return NULL;

    TreeNode *root = new TreeNode(d);
    root->left = buildTree();
    root->right = buildTree();
    return root;
}

// 二叉树的中序遍历
void inorderTraversal(TreeNode *root) {
    if (root == NULL) return;

    inorderTraversal(root->left);
    cout << root->val << " ";
    inorderTraversal(root->right);
}

int main() {
    auto root = buildTree();
    inorderTraversal(root);
    return 0;
}

Reference: https://www.codespeedy.com/build-binary-tree-in-cpp-competitive-programming

Published 308 original articles · won praise 149 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_43827595/article/details/104672938