单向链表的插入,删除,修改,查询。
单向链表的插入
1>头插法
struct node *insert(struct node *phead)
{
struct node *pnew;
pnew=(struct node *)malloc(sizeof(struct node));
printf("insert:");
scanf("%d",&pnew->data);
pnew->next=phead;//新结点指向原来的首节点
phead=pnew;//头指针指向新结点
return phead;
}
主函数中调用时 phead=insert(phead).
2>在特定结点后插入结点
struct node *insert1(struct node *phead)
{
struct node *p=phead,*pnew;
int number;
printf("请输入要插入特定数据之后:");
scanf("%d",&number);
while(p&&p->data!=number)
{
p=p->next;
}
pnew=(struct node *)malloc(sizeof(struct node));
printf("请输入要插入的数据:");
scanf("%d",&pnew->data);
pnew->next=p->next;
p->next=pnew;
return phead;
}
主函数中调用时 phead=insert(phead).
3>尾插法
struct node *insert2(struct node *phead)
{
struct node *p=phead,*pnew;
while(p&&p->next!=NULL)
p=p->next;//遍历链表,找到尾结点
printf("insert:");
pnew=(struct node *)malloc(sizeof(struct node));
scanf("%d",&pnew->data);
p->next=pnew;
pnew->next=NULL;
return phead;
}
主函数中调用时 phead=insert(phead).
单向链表的删除
struct node *dele(struct node *phead)
{
int num;
printf("dele:");
scanf("%d",&num);
struct node *p1,*p2;
p1=phead;
while(p1->next!=NULL&&p1->data!=num)
{
p2=p1;
p1=p1->next;
}
if(p1->data==num)
{
if(p1==phead)
{
phead=p1->next;
}
else
{
p2->next=p1->next;
}
free(p1);
}
return phead;
}
主函数中调用时 phead=insert(phead).
思路:遍历链表,找到你要删除的结点,连接要删除结点两边的结点,并使用free函数将p1指向的内存空间进行释放。
链表结点的修改
void change(struct node *phead)
{
struct node *p=phead;
int num,flag=0;
printf("change:");
scanf("%d",&num);
while(p!=NULL)
{
if(p->data==num)
{
flag=1;
scanf("%d",&p->data);
}
p=p->next;
}
if(flag=0)
{
printf("\n无此信息!\n");
}
}
思路:遍历链表,找到你要修改数据的结点,如未找到,说明数据中不存在你要修改的数据。
链表的查询
void search(struct node *phead)
{
struct node *p=phead;
int num,flag=0;
printf("请输入要查询的信息的数据:");
scanf("%d",&num);
while(p!=NULL)
{
if(p->data==num)
{
flag=1;
printf("%d",p->data);
}
p=p->next;
}
if(flag=0)
{
printf("\n无此信息!\n");
}
}
思路:此想法和修改的思路相似,只是在这儿是输出你所需要的信息。