如何使用值类型创建数据结构?

问题描述 投票:0回答:1

数据结构(如双链表,树和图等)需要实现引用类型的节点。通常用类和对象来实现

是否有一种方法可以在实现那些值时使用诸如struct之类的值类型?

oop data-structures linked-list value-type
1个回答
0
投票

使用struct的喜欢的列表实现:

#include <stdio.h> 
#include <stdlib.h> 

struct Node { 
    int data; 
    struct Node* next; 
}; 

// Program to create a simple linked 
// list with 3 nodes 
int main() 
{ 
    struct Node* head = NULL; 
    struct Node* second = NULL; 
    struct Node* third = NULL; 

    // allocate 3 nodes in the heap 
    head = (struct Node*)malloc(sizeof(struct Node)); 
    second = (struct Node*)malloc(sizeof(struct Node)); 
    third = (struct Node*)malloc(sizeof(struct Node)); 

    head->data = 1; // assign data in first node 
    head->next = second; // Link first node with 

    // the second node 
    // assign data to second node 
    second->data = 2; 

    // Link second node with the third node 
    second->next = third; 

    return 0; 
} 
© www.soinside.com 2019 - 2024. All rights reserved.