单链表的删除常用两种方法:
1.删除p->next的节点
{ q=p->next;
p->next=q->next;
free(q);
}
2.删除p指向的节点(需要引入前驱节点q)
{ q=head;
while(q->next!=p) q=q->next;
q->next=p->next;
free(p);
}
常采用第一种删除方式,现在展示删除p->next节点的自定义函数
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define null 0
typedef struct linknode{ //定义单链表
int data;
struct linknode *next;
}node;
node* head,* p,* q,* s;
viod creat() //创建单链表
{
head=(node*)malloc(sizeof(node));
p=head;
srand((int)time(0));
for(int i = 0; i < 10: i++){ // 长度为10
q = (node*)malloc(sizeof(node));
q->data = rand()%10 + 1; // 节点为1-10的随机数
p->next = q ;
p = q;
}q->next = null;
}
void delete() //删除p->next节点的自定义函数
{
q=p->next;
p->next=q->next;
free(q);
}
print() //打印链表
{
p=head->next;
while(p){
printf("%d\n",p->data);
p=p->next;
}
}
int main()
{
int x;
creat();
print(); //打印删除前链表
printf("请输入删除节点x:");
p=head;
while(p){
if(p->next->data==x) break;
p=p->next;
}delete();
puts("after");
print(); //打印删除后链表
return 0;
}