写一段C++语言发展单向链表的程序
时间: 2023-02-22 11:26:05 浏览: 96
用C++实现单向链表
4星 · 用户满意度95%
以下是一段简单的C语言代码,用于实现单向链表:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct node {
int data;
struct node *next;
};
// 创建链表
struct node *createList(int data) {
struct node *head = (struct node*)malloc(sizeof(struct node));
head->data = data;
head->next = NULL;
return head;
}
// 插入新节点
void insertNode(struct node *head, int data) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
// 遍历链表并打印数据
void printList(struct node *head) {
struct node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct node *head = createList(0);
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
printList(head);
return 0;
}
```
这段代码实现了创建链表、插入节点和遍历链表并打印数据的功能。希望对您有所帮助。
阅读全文