用c语言写一个链表随机插入删除的代码
时间: 2024-06-07 07:05:11 浏览: 23
可以的,请稍等一下,我给您找一下相应的代码。这是一个示例代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* head=NULL;
void display()
{
struct node* ptr;
ptr=head;
printf("\n[ ");
while(ptr!=NULL)
{
printf("(%d) ",ptr->data);
ptr=ptr->next;
}
printf(" ]");
}
void insert(int key)
{
struct node* ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=key;
ptr->next=head;
head=ptr;
}
void delete(int key)
{
struct node* temp;
struct node* prev=NULL;
temp=head;
while(temp!=NULL)
{
if(temp->data==key)
{
if(temp==head)
{
head=temp->next;
free(temp);
return;
}
else
{
prev->next=temp->next;
free(temp);
return;
}
}
else
{
prev=temp;
temp=temp->next;
}
}
}
void main()
{
int i,n,key;
printf("\nEnter the number of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
key=rand()%100;
insert(key);
}
display();
printf("\nEnter the element to be deleted:");
scanf("%d",&key);
delete(key);
display();
}
希望这个代码对您有所帮助。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)