#include <stdio.h>
#include <stdlib.h>
struct student
{
int num;
struct student * next;
};
typedef struct student STU;
typedef struct student * Link;
void create_link(Link *head)
{
*head = NULL;
}
void is_malloc_ok(Link newnode)
{
if(newnode == NULL)
{
printf("malloc error !\n");
exit(-1);
}
}
void create_newnode(Link *newnode)
{
*newnode = (Link)malloc(sizeof(STU));
is_malloc_ok(*newnode);
}
void insert_newnode(Link *head,Link newnode)
{
if(*head == NULL)
{
*head = newnode;
newnode->next = *head;
}
else
{
Link tmp;
tmp = *head;
while(tmp->next != *head)
{
tmp = tmp->next;
}
newnode->next = *head;
tmp->next = newnode;
*head = newnode;
}
}
void display(Link head)
{
Link tmp;
tmp = head;
if(head != NULL)
{
while(tmp->next != head)
{
printf("number = %d \n",tmp->num);
tmp = tmp->next;
}
if(tmp->next == head)
{
printf("number = %d \n",tmp->num);
}
}
else
{
printf("link is empty!\n");
}
}
void freelink(Link *head)
{
Link tmp;
Link head_old;
tmp = *head;
head_old = *head;
if(*head == NULL)
{
printf("Link is empty !\n");
return;
}
while(tmp->next != head_old)
{
*head = (*head)->next;
free(tmp);
tmp = (*head)->next;
}
free(tmp);
*head = NULL;
printf("free successfully !\n");
}
void insert_newnode_mid(Link *head,Link *newnode,int num)
{
Link p1,p2 = NULL;
p1 = *head;
if(*head == NULL)
{
*head = *newnode;
(*newnode)->next = *head;
}
else
{
while(p1->num < num && p1->next != *head)
{
p2 = p1;
p1 = p1->next;
}
if((*head)->next == *head)
{
if((*head)->num > num)
{
(*newnode)->next = *head;
*head = *newnode;
}
else
{
(*head)->next = *newnode;
(*newnode)->next = *head;
}
}
else
{
if(p1 == *head)
{
(*newnode)->next = *head;
*head = *newnode;
}
else
{
if(p1->next == *head)
{
if(p1->num < num)
{
p1->next = *newnode;
(*newnode)->next = NULL;
}
else
{
p2->next = *newnode;
(*newnode)->next = p1;
}
}
else
{
p2->next = *newnode;
(*newnode)->next = p1;
}
}
}
}
}
void reverslink(Link *head)
{
Link p1 = NULL;
Link p2 = NULL;
Link p3 = NULL;
p1 = *head;
if(p1 == NULL)
{
printf("Link is empty !\n");
return;
}
if(p1->next == (*head)->next)
{
return;
}
else
{
p2 = p1->next;
if(p2->next == (*head))
{
*head = p2;
p2->next = p1;
p1->next = (*head)->next;
}
else
{
p3 = p2->next;
while(p3->next != (*head)->next)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
p3->next = p2;
p1 = *head;
p1->next = (*head)->next;
*head = p3;
}
}
}
int main()
{
Link head = NULL;
Link newnode = NULL;
int i;
create_link(&head);
for(i = 0;i < 10;i++)
{
create_newnode(&newnode);
newnode->num = i;
// scanf("%d",&newnode->num);
// insert_newnode_mid(&head,&newnode,newnode->num);
insert_newnode(&head,newnode);
}
display(head);
freelink(&head);
// reverslink(&head);
display(head);
return 0;
}
循环链表
最新推荐文章于 2024-06-11 10:00:00 发布