用c语言数据结构类型写一个代码
以下是使用C语言编写的数据结构类型示例,实现了一个简单的链表:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct LinkedList {
Node *head;
int size;
} LinkedList;
LinkedList *createLinkedList() {
LinkedList *list = malloc(sizeof(LinkedList));
list->head = NULL;
list->size = 0;
return list;
}
void add(LinkedList *list, int data) {
Node *newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node *current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
list->size++;
}
void printList(LinkedList *list) {
Node *current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
LinkedList *list = createLinkedList();
add(list, 1);
add(list, 2);
add(list, 3);
printList(list);
return 0;
}
该代码定义了两个数据结构类型:Node和LinkedList。其中,Node表示链表中的节点,包含一个data成员和一个指向下一个节点的指针next成员。LinkedList表示整个链表,包含一个指向头节点的指针head和链表中节点的数量size成员。
在createLinkedList()函数中,我们使用malloc()动态分配内存,创建一个新的LinkedList结构体,并将head和size成员初始化为NULL和0。
在add()函数中,我们创建一个新的Node节点,并将data成员设置为传入的参数data。如果链表为空,则将新节点设置为头节点;否则,遍历链表,找到最后一个节点,并将其next指针指向新节点。最后,将链表中节点的数量size加1。
printList()函数用于遍历链表,并依次输出每个节点的数据成员。
在main()函数中,我们创建一个新的链表,并依次向其中添加三个节点,然后调用printList()函数输出链表中的所有节点数据。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/bhOV 著作权归作者所有。请勿转载和采集!