#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;
}
return head;
}
void Print(struct list *head)
{
while(head!=NULL)
{
printf("%d\n",head->data);
head = head->next;
}
}
struct list* Insert(struct list *head,int pos)
{
struct list *pnew,*end;
int i;
pnew = (struct list*)malloc(sizeof(struct list));
pnew->data = 100;
if(pos==0)
{
pnew->next = head;
head = pnew;
}
else
{
end = head;
if(pos>=2)
{
for(i=0;i<(pos-1);i++)
{
end = end->next;
if(end->next==NULL)
break;
}
}
pnew->next = end->next;
end->next = pnew;
}
return head;
}
struct list* Delete(struct list *head,int pos)
{
struct list *obj,*pre;
int i;
if(pos==0)
{
obj = head;
head = head->next;
free(obj);
}
else
{
pre = head;
if(pos>=2)
{
for(i=0;i<(pos-1);i++)
{
pre = pre->next;
if(pre->next==NULL)//说明给定的位置超出链表的链节数
return head;//报错并返回原head
}
}
obj = pre->next;
pre->next = obj->next;
free(obj);
}
return head;
}
int Check(struct list *head,int pos)
{
int i;
if(pos>=1)
{
for(i=0;i<pos;i++)
{
if(head->next==NULL)
return NULL;
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++)
{
if(head->next==NULL)
return;
head = head->next;
}
}
head->data = dat;
}
void main()
{
struct list *head;
head = Create();
//head = insert(head,11);
//head = Delete(head,10);
//data = Check(head,8);
Modify(head,9,300);
Print(head);
}
C语言单向链表
最新推荐文章于 2022-05-22 20:08:18 发布