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


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

      

    输入数据:3 4 -1 -1 5 -1 -1

    输出结果:4 3 5 

  • 相关阅读:
    【转】使用python编写网络通信程序
    【转】linux下的单线程
    【转】使用python进行多线程编程
    mysql数据库安装、启动及权限设置
    【转】Linux下的多线程编程背景知识
    开关电源使用
    ubi实际使用
    xshell快捷键
    Nandflash镜像尾部不应填充0xFF
    CRC校验
  • 原文地址:https://www.cnblogs.com/Allen-rg/p/13984814.html
Copyright © 2020-2023  润新知