c++数据结构类定义实现
时间: 2023-10-04 17:13:16 浏览: 65
对于 C 语言中的数据结构类定义和实现,可以通过结构体来实现。以下是一个示例:
```c
// 定义一个链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义链表类结构体
typedef struct LinkedList {
Node* head;
} LinkedList;
// 初始化链表
void initLinkedList(LinkedList* list) {
list->head = NULL;
}
// 在链表头插入节点
void insertAtHead(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = list->head;
list->head = newNode;
}
// 在链表尾插入节点
void insertAtTail(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
return;
}
Node* current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 打印链表元素
void printLinkedList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
// 释放链表内存
void freeLinkedList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
list->head = NULL;
}
```
使用以上代码,你可以创建一个链表对象并对其进行操作。例如:
```c
int main() {
LinkedList list;
initLinkedList(&list);
insertAtHead(&list, 3);
insertAtHead(&list, 2);
insertAtHead(&list, 1);
insertAtTail(&list, 4);
insertAtTail(&list, 5);
printLinkedList(&list); // 输出:1 2 3 4 5
freeLinkedList(&list);
return 0;
}
```
以上是一个简单的链表类的定义和实现示例,你可以根据需要进行扩展和修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)