c语言创建链表的方法是什么
在C语言中,创建链表通常需要定义一个结构体来表示链表的节点,然后通过动态内存分配来动态创建节点,并通过指针将节点连接起来形成链表。
以下是一个简单的示例代码,演示了如何使用C语言创建一个单向链表:
#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;}// 在链表末尾插入新节点void insertNode(struct Node** head, int data) {struct Node* newNode = createNode(data);if (*head == NULL) {*head = newNode;} else {struct Node* current = *head;while (current->next != NULL) {current = current->next;}current->next = newNode;}}// 打印链表void printList(struct Node* head) {struct Node* current = head;while (current != NULL) {printf("%d -> ", current->data);current = current->next;}printf("NULL\n");}int main() {struct Node* head = NULL;insertNode(&head, 1);insertNode(&head, 2);insertNode(&head, 3);printf("Linked list: ");printList(head);return 0;}
上述代码定义了一个包含数据和指向下一个节点的指针的链表节点结构体Node
,并实现了创建新节点、在链表末尾插入新节点和打印链表的函数。最后,在main
函数中演示了如何创建一个包含数据1、2和3的链表,并打印出链表的内容。
上一篇:没有了
c语言
webacc.exe是什么文件?webacc.exe是不是病毒
WINSYS.vbs是什么文件?WINSYS.vbs是不是病毒
winssh.exe是什么文件?winssh.exe是不是病毒
wt.exe是什么文件?wt.exe是不是病毒
winsysetm.exe是什么文件?winsysetm.exe是不是病毒
winstrve.exe是什么文件?winstrve.exe是不是病毒
winsysupd7.exe是什么文件?winsysupd7.exe是不是病毒
winsysupd.exe是什么文件?winsysupd.exe是不是病毒
winsysupd2.exe是什么文件?winsysupd2.exe是不是病毒
winsysupd8.exe是什么文件?winsysupd8.exe是不是病毒