使用c++初始化单链表
时间: 2024-01-12 19:04:37 浏览: 29
以下是使用C语言初始化单链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表节点的结构体
struct ListNode {
int val;
struct ListNode *next;
};
//初始化链表
struct ListNode* initList(int* nums, int numsSize) {
//创建头节点
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 0;
head->next = NULL;
//创建尾节点指针
struct ListNode* tail = head;
//遍历数组,创建节点并加入链表
for(int i = 0; i < numsSize; i++) {
//创建节点
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = nums[i];
node->next = NULL;
//将节点加入链表
tail->next = node;
tail = node;
}
return head->next; //返回链表的第一个节点
}
//打印链表
void printList(struct ListNode* head) {
while(head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
int numsSize = 5;
//初始化链表
struct ListNode* head = initList(nums, numsSize);
//打印链表
printList(head);
return 0;
}
```
在上面的示例代码中,我们定义了一个名为ListNode的结构体,它包含一个整数值val和一个指向下一个节点的指针next。然后我们定义了两个函数:initList和printList。initList函数用于初始化链表,它接收一个数组和数组大小作为参数,返回链表的第一个节点的指针。printList函数用于打印链表。
在main函数中,我们定义了一个整数数组nums和它的大小numsSize,然后调用initList函数初始化链表,并调用printList函数打印链表。