单链表的增删改查用c语言怎么写
时间: 2023-04-09 14:01:11 浏览: 134
对于这个问题,我可以回答。单链表的增删改查可以用C语言来实现。具体实现方法可以参考以下代码:
//定义单链表节点结构体
typedef struct Node{
int data;
struct Node *next;
}Node;
//创建单链表
Node* createList(){
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
//插入节点
void insertNode(Node *head, int data){
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = head->next;
head->next = p;
}
//删除节点
void deleteNode(Node *head, int data){
Node *p = head->next;
Node *pre = head;
while(p != NULL){
if(p->data == data){
pre->next = p->next;
free(p);
break;
}
pre = p;
p = p->next;
}
}
//修改节点
void updateNode(Node *head, int oldData, int newData){
Node *p = head->next;
while(p != NULL){
if(p->data == oldData){
p->data = newData;
break;
}
p = p->next;
}
}
//查找节点
Node* searchNode(Node *head, int data){
Node *p = head->next;
while(p != NULL){
if(p->data == data){
return p;
}
p = p->next;
}
return NULL;
}
//释放链表
void freeList(Node *head){
Node *p = head->next;
while(p != NULL){
Node *temp = p;
p = p->next;
free(temp);
}
free(head);
}
以上就是单链表的增删改查的C语言实现方法。
阅读全文
相关推荐
















