多级关联列表
- 最后更新 : 2021年8月6日
多级链接列表
多级链接列表是一种二维数据结构,由多个链接列表组成,多级链接列表中的每个节点都有一个下一个和子节点指针。所有的元素都是使用指针链接的。
多级链表
表示方法:
一个多级链表由一个指向链表第一个节点的指针表示。与链表类似,第一个节点被称为头。如果多级链表是空的,那么head的值就是NULL。列表中的每个节点至少由三部分组成:
1. 数据。
**2.**指向下一个节点的指针。
3. 指向子节点的指针。
一个多级链表的每个节点表示为。
class Node
{
public:
int data;
Node *next;
Node *child;
}。
下面是多级链表的实现
C++
// C++ program to implement// a multilevel linked list#include <bits/stdc++.h>using namespace std;// Representation of nodeclass Node {public:int data;Node* next;Node* child;};// A function to create a linked list// with n(size) nodes returns head pointerNode* createList(int* arr,int n){Node* head = NULL;Node* tmp;// Traversing the passed arrayfor (int i = 0; i < n; i++) {// Creating a node if the list// is emptyif (head == NULL) {tmp = head =new Node();}else {tmp->next =new Node();tmp = tmp->next;}// Created a node with data and// setting child and next pointer// as NULL.tmp->data = arr[i];tmp->next = tmp->child = NULL;}return head;}// To print the linked listvoid printMultiLevelList(Node* head){// While head is not nullwhile (head) {if (head->child) {printMultiLevelList(head->child);}cout << head->data <<" ";head = head->next;}}// Driver codeint main(){// Initializing the data in arrays(row wise)int arr1[3] = { 1, 2, 3 };int arr2[2] = { 5, 6 };int arr3[1] = { 4 };int arr4[3] = { 7, 8, 9 };// creating Four linked lists// Passing array and size of array// as parametersNode* head1 = createList(arr1, 3);Node* head2 = createList(arr2, 2);Node* head3 = createList(arr3, 1);Node* head4 = createList(arr4, 3);// Initializing children and next pointers// as shown in given diagramhead1->child = head2;head1->next->next->child = head3;head2->next->child = head4;// Creating a null pointer.Node* head = NULL;head = head1;// Function Call to printprintMultiLevelList(head);return 0;} |
输出
5 7 8 9 6 1 2 4 3
读者请注意!现在不要停止学习。以学生可接受的价格获得所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 箭头_下降_上升
保存