#include <stdio.h>
#include "./LinkList.h"
#include <stdlib.h>
/*
* function: 创建循环链表
* @param [ in]
* @param [out]
* @return
*/
LinkLIst *linkList(void)
{
LinkLIst *head =(LinkLIst*)malloc(sizeof(LinkLIst));
if (NULL==head)
{
printf("头结点申请失败,链表创建失败\n");
return NULL;
}
printf("链表创建成功\n");
head->data.len=0;//头结点链表长度初始化
head->next=head;
return head;
}
/*
* function: 头部法插入数据
* @param [ in]
* @param [out]
* @return
*/
void insert_head(LinkLIst *head,datatype num)
{
LinkLIst *temp=(LinkLIst*)malloc(sizeof(LinkLIst));
if(NULL==temp)
{
printf("创建新节点失败,插入失败\n");
return;
}
temp->data.text=num;//将结点进行初始化
temp->next=NULL;
temp->next=head->next;//将新的节点插入链表
head->next=temp;
head->data.len++;//更新结点中链表的长度
return;
}
/*
* function: 遍历链表
* @param [ in]
* @param [out]
* @return
*/
void show_list(LinkLIst *head)
{
LinkLIst *p=head->next;
while(p!=head)
{
printf("%d\t",p->data.text);
p=p->next;
}
printf("\n");
return;
}
/*
* function: 尾插法
* @param [ in]
* @param [out]
* @return
*/
void insert_rear(LinkLIst *head,datatype num)
{
LinkLIst *temp=(LinkLIst*)malloc(sizeof(LinkLIst));
if(NULL==temp)
{
printf("创建新节点失败,插入失败\n");
return;
}
temp->data.text=num;//将结点进行初始化
temp->next=NULL;
LinkLIst *p=head;
/*while(p->next!=NULL)//找到尾结点
{
p=p->next;
}
p->next =temp;//插入数据8*/
while(p->next!=head)
{
p=p->next;
}
temp->next=p->next;
p->next=temp;
head->data.len++;//更新链表长度
return;
}
/*
* function: 头删法
* @param [ in]
* @param [out]
* @return
*/
void delete_head(LinkLIst *head)
{
//判断链表是否为空
if(head->next==NULL)
{
printf("链表为空,删除失败\n");
return;
}
//p=head->next
LinkLIst *p=head;
p=head->next;
head->next=p->next;
free(p);
p=NULL;
head->data.len--;
return;
}
/*
* function: 尾删法
* @param [ in]
* @param [out]
* @return
*/
void delete_rear(LinkLIst *head)
{
//判断链表是否为空
if(head->next==NULL)
{
printf("链表为空,删除失败\n");
return;
}
LinkLIst *p=head;
while(p->next->next!=head)
{
p=p->next;
}
// datatype num =p->next->data.text;
LinkLIst *q=p->next;
p->next=q->next;
datatype num=q->data.text;
free(q);
q=NULL;
head->data.len--;
return;
}
#include <stdio.h>
#include "./LinkList.h"
int main(int argc, const char *argv[])
{
LinkLIst* head=linkList();
insert_head(head,5);
insert_head(head,3);
insert_head(head,6);
insert_head(head,80);
show_list(head);
insert_rear(head,4);
show_list(head);
delete_head(head);
show_list(head);
delete_rear(head);
show_list(head);
return 0;
}