单向链表的相关操作

单向链表的插入,删除,修改,查询。

单向链表的插入

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");
 }
}

思路:此想法和修改的思路相似,只是在这儿是输出你所需要的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值