创建单链表的代码csdn
时间: 2023-08-21 15:00:31 浏览: 50
创建单链表的代码如下:
```cpp
#include<iostream>
using namespace std;
// 定义链表节点的结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 创建单链表
ListNode* createLinkedList(int arr[], int n) {
if (n == 0) {
return NULL;
}
ListNode* head = new ListNode(arr[0]); // 头节点
ListNode* curNode = head;
for (int i = 1; i < n; i++) {
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
// 打印单链表
void printLinkedList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
// 测试链表的创建和打印
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(int);
ListNode* head = createLinkedList(arr, n);
printLinkedList(head);
return 0;
}
```
以上代码首先定义了链表节点的结构体,其中包括节点的值和指向下一个节点的指针。然后通过`createLinkedList`函数创建单链表,参数为一个整型数组和数组的长度,返回头节点。在`createLinkedList`函数中,先判断长度是否为0,若是,则返回空指针。然后循环遍历数组,逐个创建新的节点,并将节点连接起来。最后返回头节点。`printLinkedList`函数用于打印链表的值。在`main`函数中,首先创建一个整型数组,然后调用`createLinkedList`函数创建链表,最后调用`printLinkedList`函数打印链表的值。