单链表的增删查改代码:
1.创建结构体
// 结构体类型的创建
struct node
{int data; // 数据域struct node *next; // 指针域
};
2.创建节点,节点的存储在malloc申请的空间内,也就是堆空间。
// 创建节点
struct node *create_node(int data)
{struct node *xnew = malloc(sizeof(struct node));if (xnew == NULL){perror("创建失败\n");}xnew->data = data;xnew->next = xnew;return xnew; // 返回xnew的地址
}
3.头插入节点,先让节点指向头,在让头节点指向新节点
// 头插入节点
void top(struct node *head, struct node *xnew)
{xnew->next = head->next;head->next = xnew;
}
4.尾插法,定义一个游走的节点,让该节点偏移到单链表的最后一个节点,再让该游走节点指向新节点,并且使新的节点指向头节点,实现单链表循环
// 尾插法
void wei(struct node *head, struct node *xnew)
{struct node *pos = head->next;// 让节点走起来 不断地走到下一位while (pos->next != head){pos = pos->next;}pos->next = xnew;xnew->next = head;
}
5.显示节点数据函数,同样定义一个游走的节点,先让其指向头节点的下一位,再让其走过单链表的每个一个节点,并答应出来
// 显示节点
void show_node(struct node *head)
{struct node *pos = head->next;while (pos != head){printf("%d ", pos->data);pos = pos->next;}printf("\n");
}
6.删除节点,我们同意定义一个游走的节点指针,让该节点走过单链表并逐一判断是否是我们要删除的节点,如果是则退出来,并用一个新的节点指针p来指向该地址,在设计游走节点的时候使用pos->next-data,这样可以让节点始终停留在节点p的上一位,并让该指针pos指向节点p的下一位,然后让节点p指向NULL,并释放堆内存
// 删除节点
void delete_node(struct node *head, int data)
{struct node *pos = head->next;while (pos->next->data != data){pos = pos->next;}struct node *p = pos->next;pos->next = p->next;p->next = NULL;free(p);
}
7.修改节点,定义一个游走的节点指针,让该节点游走单链表,如果找到了我们要的数据,那就赋值进行修改。
// 修改节点
void modify_node(struct node *head, int data, int new_data)
{struct node *pos = head->next;while(pos->data != data){pos = pos->next;}pos->data = new_data;}
完整代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 结构体类型的创建
struct node
{int data; // 数据域struct node *next; // 指针域
};// 创建节点
struct node *create_node(int data)
{struct node *xnew = malloc(sizeof(struct node));if (xnew == NULL){perror("创建失败\n");}xnew->data = data;xnew->next = xnew;return xnew; // 返回xnew的地址
}
// 头插入节点
void top(struct node *head, struct node *xnew)
{xnew->next = head->next;head->next = xnew;
}
// 尾插法
void wei(struct node *head, struct node *xnew)
{struct node *pos = head->next;// 让节点走起来 不断地走到下一位while (pos->next != head){pos = pos->next;}pos->next = xnew;xnew->next = head;
}
// 显示节点
void show_node(struct node *head)
{struct node *pos = head->next;while (pos != head){printf("%d ", pos->data);pos = pos->next;}printf("\n");
}
// 删除节点
void delete_node(struct node *head, int data)
{struct node *pos = head->next;while (pos->next->data != data){pos = pos->next;}struct node *p = pos->next;pos->next = p->next;p->next = NULL;free(p);
}
// 修改节点
void modify_node(struct node *head, int data, int new_data)
{struct node *pos = head->next;while(pos->data != data){pos = pos->next;}pos->data = new_data;}
//主函数
int main()
{struct node *head = create_node(0);for (int i = 1; i < 10; i++){top(head, create_node(i));}show_node(head);delete_node(head, 3);show_node(head);modify_node(head,2,999);show_node(head);
}