链表的基本操作(动态链表)

初始化链表

#include<string.h>
#include<stdio.h>
#include<stdlib.h>
​
​
typedef struct node{
  char name[20];
  double score;
  struct node* next;
}Node;
​
//初始化头节点,并返回头指针
Node* list_init()
{
  Node* head = (Node*)malloc(sizeof(Node));
    //查看空间是否开辟
  if(head==NULL)
  {
     return NULL;
  }
    //头节点可以不放数据
  strcpy(head->name,"acs");
  head->score=0.0;
  head->next=NULL;
​
  return head;
  //创建了一个节点,并且head指向它,这个节点指向空
}
​

头插法

//头插法,插入节点
void head_insert(Node* head,char* p,double s)
{
  Node* new_node = (Node*)malloc(sizeof(Node));
​
  strcpy(new_node->name,p);
  new_node->score=s;
  new_node->next=NULL;
  
  new_node->next = head->next;
  head->next = new_node;
​
}

尾插法

//尾插法,插入节点
void tail_insert(Node* head,char* p,double s)
{
  Node* new_node = (Node*)malloc(sizeof(Node));
  Node* pp = head;
​
​
  strcpy(new_node->name,p);
  new_node->score=s;
  new_node->next=NULL;
​
  while(pp->next!=NULL)
  {
    pp=pp->next;
  }
​
  pp->next = new_node;
}

遍历并打印

//实现打印功能
void print_list(Node* head)
{
  Node* p = head;
​
  while(p->next!=NULL)
  {
    p=p->next;
    printf("%s  %f\n",p->name,p->score);
  }
}
​

计算链表节点数

//计算链表中有多少个节点
int node_num(Node* head)
{
  Node* p = head;
  int count=0;
  while(p!=NULL)
  {
    p=p->next;
    count++;
  }
  return count;
​
}

主函数的调用

​
int main()
{
   Node* head=list_init();
   
   
   head_insert(head,"张三",88.5);
   head_insert(head,"李四",99.0);
   head_insert(head,"王五",80.0);
   head_insert(head,"长空",100.5);
   head_insert(head,"小凡",60.4);
   
​
   tail_insert(head,"天了",88.4);
   tail_insert(head,"小白",78.9);
​
   print_list(head);
    
   int num =  node_num(head);
   printf("一共有%d个节点\n",num);
​
​
   return 0;
}
​
​

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值