环形链表的实现

link.h

#ifndef _LINK_H
#define _LINK_H
struct student{
    int age;
    char name[10];
    struct student *next;
};

typedef struct student info_t;

extern info_t *head;

#endif

link.c

#include "link.h"
#include <malloc.h>
#include <string.h>
#include <stdio.h>

info_t *init(char *name,int age)
{

    info_t* p = (info_t*)malloc(sizeof(info_t));
    if(p == NULL){
        printf("malloc fail\n");
        return NULL;
    }
    memset(p->name,'\0',sizeof(p->name));
    strncpy(p->name,name,strlen(name));
    p->age = age;
    p->next = NULL;
    return p;
}

void addTail(info_t *p)
{
    info_t *head_p = NULL;
    if(head == NULL){
      head = p;
      p->next = head;
      return;
    }
    head_p = head;
    do{
     head_p = head_p->next;
    }while(head_p->next != head);

    head_p->next = p;
    p->next = head;

}

void addFront(info_t* p)
{
  info_t* head_p = NULL;
  head_p = head;
  if(head_p == NULL){
      head = p;
      p->next = head;
      return;
  }
    head_p = head;
    do{
     head_p = head_p->next;
    }while(head_p->next != head);

    head_p->next = p;
    p->next = head;
    head = p;
}

void traverse()
{
    info_t *head_p = head;
    if(head_p == NULL)
        printf("list is NULL\n");
    do{
     printf("name:%s,age:%d\n",head_p->name,head_p->age);
     head_p = head_p->next;
    }while(head_p!= head);


}

info_t *find (char *name,int age)
{
    info_t *head_p = head;
    if(head_p == NULL){
      printf("list is NULL\n");
        return NULL;
    }

    do{
     if(strncmp(head_p->name,name,strlen(head_p->name)) == 0 && head_p->age == age)
        return head_p;
     head_p = head_p->next;
    }while(head_p  != head);
    printf("lala\n");
    return NULL;
}

info_t *del(char *name, int age)
{
    info_t *p = NULL;
    info_t *head_p = head;
    if(head == NULL)
        return NULL;
    p = find(name,age);
    if(p == NULL)
        return NULL;
    if(p == head){
        do{
           head_p = head_p->next;
        }while(head_p->next != head);
        head_p->next = head->next;
        free(head);
        head = head_p->next;
    }else{
        do{
        head_p = head_p->next;
        }while(head_p->next != p);
        head_p->next = p->next;
        free(p);
    }

}

mian.c

#include <stdio.h>
#include "link.h"

info_t *head = NULL;

int main()
{
    info_t * p = init("carl",10);
    addTail(p);
    p = init("nana",24);
    addTail(p);
    p = init("wkf",25);
    addTail(p);
    p = init("nihao",27);
    addTail(p);
    p = init("nimei",45);
    addFront(p);
    traverse();
    p = del("nimei",45);
    traverse();


}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值