2024年4月30日发(作者:)
C语言中静态链表的基本操作包括:
1. 初始化链表
2. 创建节点
3. 插入节点
4. 删除节点
5. 遍历链表
6. 销毁链表
以下是一个简单的静态链表实现:
```c
#include
#include
typedef struct Node {
int data;
struct Node next;
} Node;
// 初始化链表
Node initList() {
Node head = (Node )malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 创建节点
Node createNode(int data) {
Node newNode = (Node )malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点
void insertNode(Node head, int data, int position) {
Node newNode = createNode(data);
Node temp = head;
int i;
for (i = 0; i < position && temp->next != NULL; i++) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
// 删除节点
void deleteNode(Node head, int position) {
Node temp = head;
int i;
for (i = 0; i < position - 1 && temp->next != NULL; i++) {
temp = temp->next;
}
if (temp->next != NULL) {
Node delNode = temp->next;
temp->next = delNode->next;
free(delNode);
}
}
// 遍历链表
void traverseList(Node head) {
Node temp = head->next;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("
");
}
// 销毁链表
void destroyList(Node head) {
Node temp = head;
while (temp != NULL) {
Node delNode = temp;
temp = temp->next;
free(delNode);
}
}
int main() {
Node head = initList();
insertNode(head, 1, 0);
insertNode(head, 2, 1);
insertNode(head, 3, 2);
traverseList(head);
deleteNode(head, 1);
traverseList(head);
destroyList(head);
return 0;
}
```
这个示例中,我们定义了一个静态链表结构体`Node`,并实现了初始化链表、创建节点、
插入节点、删除节点、遍历链表和销毁链表等基本操作。在`main`函数中,我们创建了一个
链表,插入了一些节点,然后遍历链表,删除一个节点,再次遍历链表,最后销毁链表。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1714416116a2442185.html
评论列表(0条)