如何用c++创建单链表
时间: 2023-05-11 13:02:00 浏览: 100
可以使用以下代码来创建单链表:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
struct Node* createLinkedList(int arr[], int n) {
struct Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
struct Node* newNode = createNode(arr[i]);
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printLinkedList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
struct Node* head = createLinkedList(arr, n);
printLinkedList(head);
return 0;
}
```
这段代码定义了一个 `Node` 结构体,包含一个整数数据和一个指向下一个节点的指针。`createNode` 函数用于创建一个新节点,`createLinkedList` 函数用于创建一个包含给定数据的单链表,`printLinkedList` 函数用于打印链表中的所有数据。在 `main` 函数中,我们创建一个整数数组,然后使用 `createLinkedList` 函数创建一个单链表,并使用 `printLinkedList` 函数打印链表中的所有数据。