动态链表的创建主要包括以下几个步骤:
- 定义链表节点的数据结构:
typedef struct Node{ int data; // 节点存储的数据 struct Node* next; // 指向下一个节点的指针 }Node;
- 创建链表的头节点:
Node* createList(){ Node* head = (Node*)malloc(sizeof(Node)); // 为头节点分配内存空间 if(head == NULL){ printf("内存分配失败!\n"); exit(1); } head->next = NULL; // 头节点的next指针置空 return head; }
- 插入节点到链表中:
void insertNode(Node* head, int data){ Node* newNode = (Node*)malloc(sizeof(Node)); // 为新节点分配内存空间 if(newNode == NULL){ printf("内存分配失败!\n"); exit(1); } newNode->data = https://www.yisu.com/ask/data; // 将数据赋值给新节点>next = head->next; // 使新节点的next指针指向原来的第一个节点 head->next = newNode; // 使头节点的next指针指向新节点 }
- 打印链表的所有节点:
void printList(Node* head){ Node* p = head->next; // 从第一个节点开始遍历 while(p != NULL){ printf("%d ", p->data); // 打印节点数据 p = p->next; // 指针移动到下一个节点 } printf("\n"); }
以下是一个完整的示例代码:
#include#include typedef struct Node{ int data; struct Node* next; }Node; Node* createList(){ Node* head = (Node*)malloc(sizeof(Node)); if(head == NULL){ printf("内存分配失败!\n"); exit(1); } head->next = NULL; return head; } void insertNode(Node* head, int data){ Node* newNode = (Node*)malloc(sizeof(Node)); if(newNode == NULL){ printf("内存分配失败!\n"); exit(1); } newNode->data = https://www.yisu.com/ask/data;>next = head->next; head->next = newNode; } void printList(Node* head){ Node* p = head->next; while(p != NULL){ printf("%d ", p->data); p = p->next; } printf("\n"); } int main() { Node* head = createList(); insertNode(head, 1); insertNode(head, 2); insertNode(head, 3); insertNode(head, 4); printList(head); return 0; }
运行结果为:
4 3 2 1