链表是一种罕见的数据构造,它在C言语编程中尤为重要。本教案旨在帮助初学者跟进阶者深刻懂得链表的不雅点、实现跟利用,经由过程一系列的实战练习,让你轻松驾驭链表编程。
链表是一种由一系列节点构成的线性数据构造,每个节点包含数据跟指向下一个节点的指针。
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
if (head == NULL) {
exit(-1);
}
head->next = NULL;
return head;
}
void insertNode(Node* head, int data, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (position == 0) {
newNode->next = head->next;
head->next = newNode;
} else {
Node* current = head;
for (int i = 0; current != NULL && i < position - 1; i++) {
current = current->next;
}
if (current == NULL) {
return;
}
newNode->next = current->next;
current->next = newNode;
}
}
void deleteNode(Node* head, int position) {
if (head == NULL) {
return;
}
if (position == 0) {
Node* temp = head;
head = head->next;
free(temp);
} else {
Node* current = head;
for (int i = 0; current->next != NULL && i < position - 1; i++) {
current = current->next;
}
if (current->next == NULL) {
return;
}
Node* temp = current->next;
current->next = temp->next;
free(temp);
}
}
void traverseList(Node* head) {
Node* current = head->next;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
typedef struct DNode {
int data;
struct DNode* prev;
struct DNode* next;
} DNode;
typedef struct CNode {
int data;
struct CNode* next;
} CNode;
链表是C言语编程中非常重要的一种数据构造,经由过程本教案的进修,信赖你曾经控制了链表的基本不雅点跟实现方法。持续现实跟摸索,你将可能更纯熟地应用链表处理现实成绩。