動態(tài)鏈表的創(chuàng)建主要包括以下幾個步驟:
typedef struct Node{
int data; // 節(jié)點(diǎn)存儲的數(shù)據(jù)
struct Node* next; // 指向下一個節(jié)點(diǎn)的指針
}Node;
Node* createList(){
Node* head = (Node*)malloc(sizeof(Node)); // 為頭節(jié)點(diǎn)分配內(nèi)存空間
if(head == NULL){
printf("內(nèi)存分配失??!\n");
exit(1);
}
head->next = NULL; // 頭節(jié)點(diǎn)的next指針置空
return head;
}
void insertNode(Node* head, int data){
Node* newNode = (Node*)malloc(sizeof(Node)); // 為新節(jié)點(diǎn)分配內(nèi)存空間
if(newNode == NULL){
printf("內(nèi)存分配失?。n");
exit(1);
}
newNode->data = data; // 將數(shù)據(jù)賦值給新節(jié)點(diǎn)
newNode->next = head->next; // 使新節(jié)點(diǎn)的next指針指向原來的第一個節(jié)點(diǎn)
head->next = newNode; // 使頭節(jié)點(diǎn)的next指針指向新節(jié)點(diǎn)
}
void printList(Node* head){
Node* p = head->next; // 從第一個節(jié)點(diǎn)開始遍歷
while(p != NULL){
printf("%d ", p->data); // 打印節(jié)點(diǎn)數(shù)據(jù)
p = p->next; // 指針移動到下一個節(jié)點(diǎn)
}
printf("\n");
}
以下是一個完整的示例代碼:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* createList(){
Node* head = (Node*)malloc(sizeof(Node));
if(head == NULL){
printf("內(nèi)存分配失??!\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èi)存分配失??!\n");
exit(1);
}
newNode->data = data;
newNode->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;
}
運(yùn)行結(jié)果為:
4 3 2 1