鄂尔多斯市建设网站,wordpress自动插件,wordpress怎么首页幻灯片,最好的免费推广平台前言
链表是最基础的数据结构#xff0c;可以用于实现栈、队列等等。
实现原理 节点#xff08;Node#xff09;#xff1a;链表的基本构建单元是节点#xff0c;每个节点包含两部分#xff1a;数据和指向下一个节点的指针。在C语言中#xff0c;节点通常用结构体来表…前言
链表是最基础的数据结构可以用于实现栈、队列等等。
实现原理 节点Node链表的基本构建单元是节点每个节点包含两部分数据和指向下一个节点的指针。在C语言中节点通常用结构体来表示结构体中包含数据字段和指针字段。
struct Node {int data;struct Node* next;
};头指针Head Pointer链表的起始节点被称为头节点。头指针是指向链表第一个节点的指针。通过头指针可以访问整个链表。 尾节点Tail Node链表中最后一个节点称为尾节点。它的指针通常指向NULL表示链表的结束。 指针连接链表中的节点通过指针相互连接。每个节点的指针指向下一个节点形成一个链式结构。 动画演示过程
Linked List Stack Visualization
头插法
#include stdio.h
#include stdlib.h// 定义链表节点结构
struct Node {int data;struct Node* next;
};// 创建新节点
struct Node* createNode(int data) {struct Node* newNode (struct Node*)malloc(sizeof(struct Node));if (newNode NULL) {printf(Memory allocation failed!\n);exit(1);}newNode-data data;newNode-next NULL;return newNode;
}// 头插法插入新节点
void insertFront(struct Node** head, int data) {struct Node* newNode createNode(data);newNode-next *head;*head newNode;
}// 打印链表
void printList(struct Node* head) {struct Node* temp head;while (temp ! NULL) {printf(%d - , temp-data);temp temp-next;}printf(NULL\n);
}// 主函数
int main() {struct Node* head NULL;// 使用头插法插入一些节点insertFront(head, 3);insertFront(head, 2);insertFront(head, 1);printf(List after using head insertion: );printList(head);return 0;
}尾插法
#include stdio.h
#include stdlib.h// 定义链表节点结构
struct Node {int data;struct Node* next;
};// 创建新节点
struct Node* createNode(int data) {struct Node* newNode (struct Node*)malloc(sizeof(struct Node));if (newNode NULL) {printf(Memory allocation failed!\n);exit(1);}newNode-data data;newNode-next NULL;return newNode;
}// 在链表末尾插入新节点
void insertEnd(struct Node** head, int data) {struct Node* newNode createNode(data);if (*head NULL) {*head newNode;} else {struct Node* temp *head;while (temp-next ! NULL) {temp temp-next;}temp-next newNode;}
}// 删除指定值的节点
void deleteNode(struct Node** head, int key) {struct Node* temp *head;struct Node* prev NULL;if (temp ! NULL temp-data key) {*head temp-next;free(temp);return;}while (temp ! NULL temp-data ! key) {prev temp;temp temp-next;}if (temp NULL) {printf(Node with value %d not found!\n, key);return;}prev-next temp-next;free(temp);
}// 打印链表
void printList(struct Node* head) {struct Node* temp head;while (temp ! NULL) {printf(%d - , temp-data);temp temp-next;}printf(NULL\n);
}// 主函数
int main() {struct Node* head NULL;// 插入一些节点insertEnd(head, 1);insertEnd(head, 2);insertEnd(head, 3);printf(Initial List: );printList(head);// 删除节点deleteNode(head, 2);printf(List after deleting node with value 2: );printList(head);return 0;
}