首页 > 编程语言 > 详细

创建单链表、双链表、二叉树(C++)

时间:2020-11-16 14:44:52      阅读:27      评论:0      收藏:0      [点我收藏+]

https://blog.csdn.net/qq_43827595/article/details/104672938

链表创建:

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

  

 

二叉树创建:

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

  

创建单链表、双链表、二叉树(C++)

原文:https://www.cnblogs.com/Allen-rg/p/13984814.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!