单链表

实现动态链表的创建、删除、插入释放等功能

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)

int n;
struct student
{
  char name[15];
  int score;
  struct student *next;
};

struct student *creat()
{
  struct student*p2,*p1,*head;
  n=0;
  p1 = p2 = (struct student *)malloc(LEN);
  scanf ("%s",&(p1->name));
  scanf ("%d",&(p1->score));
  head = NULL;
  while(p1->score!=0)
  {
    if((++n)==1) head=p1;
    else p2->next=p1;
    p2=p1;
    p1 = (struct student *) malloc (LEN);
    scanf ("%s",&(p1->name));
    scanf ("%d",&(p1->score));
  }
  p2->next = NULL;
  return(head);
}

void print(struct student *head)
{
  struct student *p;
  p=head;
  if(head!=NULL)
  do
  {
    printf("%s  %d\n",p->name,p->score);
    p=p->next;
  } while(p!=NULL);
}

void my_free(struct student *head)
{
  struct student *p;
  while(head != NULL)
  {
    p = head;
    head = head->next;
    free(p);
    p = NULL;
  }
}

void del(struct student *head,int n)
{
  struct student *p_curr,*p_last;
  int num = 1;
  p_curr = head;
  while(p_curr != NULL)
  {
    num++;
    p_last = p_curr;
    p_curr = p_curr->next;
    if(num == n)
    {
      p_last->next = p_curr->next;
      free(p_curr);
      p_curr = NULL;
    }
  }
}

void insert(struct student *head, int n, char str_name[], int e)
{
  struct student *p_last,*p_curr,*p_inst;
  int num = 1;
  p_inst = (struct student *)malloc(sizeof(struct student));
  strcpy(p_inst->name, str_name);//字符数组的复制所用的函数
  p_inst->score = e;
  p_inst->next = NULL;

  p_curr = head;
  while(p_curr->next != NULL)
  {
    num++;
    p_last = p_curr;
    p_curr = p_curr->next;
    if(num == n)
    {
      p_last->next = p_inst;
      p_inst->next = p_curr;
      break;//一定要有这个,执行完这个就不在执行下去了
    }
  }
}

void main()
{
  struct student *head;
  head=creat();
  print(head);
  del(head,2);
  print(head);
  insert(head, 2, "sun", 99);
  print(head);
  my_free(head);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值