链表简介,Linux环境下创建一个静态链表,计算链表的节点总数、查找对应节点、在节点后面和前面插入节点,删除节点

链表的每个节点应由数据和一个结构体指针组成。其中,前一个节点的结构体指针应该指向后一个节点。

创建一个链表:

首先定义一个结构体,其中需要包含一个指向自己的结构体指针;

struct Test
{
 int num;
 struct Test *next;
};

 定义节点,将节点联系起来;

 struct Test s1 = {1,NULL};
 struct Test s2 = {2,NULL};
 struct Test s3 = {3,NULL};

 s1.next = &s2;
 s2.next = &s3;

遍历一个链表:

void printLink(struct Test *head)
{
  struct Test *point;
  point = head;

  while(1)
  {
   if(point != NULL)
   {
    printf("%d ",point->num);
    point = point->next;
   }
   else{
    putchar('\n');
    break;
   }
  }
}

计算链表的节点总数:

int findLinkNodeNum(struct Test *head)
{
 int cnt = 0;
 while(head != NULL){
  cnt++;
  head = head->next;
 }
 return cnt;
}

查找链表中有没有这个节点:

int searchLinkNode(struct Test *head,int data)
{
 while(head != NULL){
  if(head->num == data){
   return 1;
  }
  head = head->next;
 }
 return 0;
}

在对应节点后面插入一个新的节点:

int insertFromBehind(struct Test *head,int data,struct Test *new)
{
   struct Test *p = head;
   while(p != NULL){
     if(p->num == data){
        new->next = p->next;
        p->next = new;
        return 1;
     }
   p = p->next;
  }
  return 0;
}

在对应节点前面插入节点:

注意事项:在节点前面插入节点分为两种情况

                  第一种是在头结点前面插入,这种情况会改变头结点的位置

                  第二种情况就是在其他节点前面插入。

代码如下:

struct Test* insertFromFor(struct Test *head,int data,struct Test *new)
{
     struct Test *p = head;
     if(p->num == data){     //在头结点前面插入
          new->next = p;
          return new;
     }
     while(p->next != NULL){   //在其他节点前面插入
             if(p->next->num == data){
                    new->next = p->next;
                    p->next = new;
                    return head;
             }
      p = p->next;
     }
     return head;
}

还有一个需要注意的点是,在b节点前面插入一个c节点,需要找到b节点前面的a节点,然后先把

c->next = a->next;然后 a->next = c。所以在代码中的循环判断条件与在节点后面插入的循环判断条件有所不同。

 删除对应的节点:

逻辑和在节点前面插入节点相似;分为删除头结点和其他节点两种情况。也是需要先找到删除的b节点的前一个a节点,然后令a->next = a-z.next->next;返回头结点。。

文章内若有错误,敬请指出,互相交流,共同进步!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hardStudy_h

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值