链表
删除元素:
struct no *shead; //设置虚拟头节点方便进行代码的添加与删除操作
shead = (struct no *)malloc(sizeof(struct no));
shead->next = head;
struct no *cur = shead;
while(cur->next != NULL){
if (cur->next->val == val){
struct no *tmp = cur->next; // tmp指针指向所需删除的元素空间
cur->next = cur->next->next;
// 将cur指向的元素中的next重新指向cur下下个元素(cur下个元素即所需删除的元素)
free(tmp); // 释放需要删除的元素空间
}
else{
cur = cur->next; // cur指向下一个元素
}
}
head = shead->next; / / 头指针重新指向防止之前的循环删除了头元素的情况
free(shead); / / 释放虚拟指针
元素插入
struct no{
int data;
struct no *next;
}*head;
头插法:
不带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));
cur->data=a;
cur->next=head;
head=cur;
带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));
cur->data=a;
cur->next=head->next;
head->next=cur;
尾插法:
不带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));
cur->data=a;
cur->next=NULL; // 由于是尾插法,结尾元素的next指向一定为NULL
if(head==NULL){
head=cur;
}else {
struct no *last =head;
while(last->next!=NULL){
last=last->next;
}
last->next=cur;
}
带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));
cur->data=a;
cur->next=NULL; // 由于是尾插法,结尾元素的next指向一定为NULL
struct no *last =head;
while(last->next!=NULL){
last=last->next;
}
last->next=cur;
head->data=head->data+1;//此句是利用头节点中1的data来记录该链表的有效元素数量
}