創建單鏈表的基本思路如下:
struct ListNode {
int data;
struct ListNode* next;
};
struct ListNode* createList() {
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
return head;
}
void addNode(struct ListNode* head, int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->data = value;
newNode->next = head->next;
head->next = newNode;
}
void printList(struct ListNode* head) {
struct ListNode* node = head->next;
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
通過以上步驟,就可以創建一個簡單的單鏈表,并向其中添加節點。