#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
struct list* Create()
{
struct list *head,*pnew,*end;
int number = 10;
int i;
head = (struct list*)malloc(sizeof(struct list));
head->data = 0;
head->next = NULL;
end = head;
for(i=1;i<number;i++)
{
pnew = (struct list*)malloc(sizeof(struct list));
pnew->data = i;
pnew->next = NULL;
end->next = pnew;
end = end->next;
}
pnew->next = head;//最后一个节点的指针指向head
return head;
}
struct list* Insert(struct list *head,int pos)
{
struct list *pnew,*end,*temp;
int i;
pnew = (struct list*)malloc(sizeof(struct list));
pnew->data = 100;
if(pos==0)//在0的位置插入,就相当于在尾部追加
{
temp = head;
do
{
temp = temp->next;
}while(temp->next!=head);
temp->next = pnew;
pnew->next = head;
head = pnew;
}
else
{
end = head;
if(pos>=2)
{
for(i=0;i<(pos-1);i++)
{
end = end->next;
}
}
pnew->next = end->next;
end->next = pnew;
}
return head;
}
struct list* Delete(struct list *head,int pos)
{
struct list *obj,*pre,*temp;
int i;
if(pos==0)
{
pre = head;
do
{
pre = pre->next;
}while(pre->next!=head);//找到最后一个链节,也就是head前一个链节
temp = head->next;
pre->next = head->next;
free(head);
head = temp;
}
else
{
obj = head;
if(pos>=1)
{
for(i=0;i<pos;i++)
{
pre = obj;//记录前一个链节
obj = obj->next;
}
}
pre->next = obj->next;
if(obj==head)
head = head->next;//如果被删除的是head,那么新head为原head下一个链节
free(obj);
}
return head;
}
void Print(struct list *head)
{
struct list *temp;
temp = head;
printf("%d\n",temp->data);
do
{
temp = temp->next;
printf("%d\n",temp->data);
}while(temp->next!=head);//如果再次循环到head处,则停止输出
}
int Check(struct list *head,int pos)
{
int i;
if(pos>=1)
{
for(i=0;i<pos;i++)
head = head->next;
}
return head->data;
}
void Modify(struct list *head,int pos,int dat)
{
int i;
if(pos>=1)
{
for(i=0;i<pos;i++)
head = head->next;
}
head->data=dat;
}
void main()
{
struct list *head;
head = Create();
Modify(head,5,300);
Print(head);
}
C语言单向环形链表
最新推荐文章于 2024-05-05 16:51:47 发布