在C语言中,创建一个空的链表需要以下步骤:
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
完整示例代码:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
int i;
for (i = 1; i <= 5; i++) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
printf("Linked List: ");
printList(head);
return 0;
}
此代码段将创建一个包含1到5的链表,并将其打印出来。
注意:这只是链表的基本操作示例,实际使用中可能还涉及其他操作,例如删除节点、插入节点等。
领取专属 10元无门槛券
手把手带您无忧上云