#include <stdio.h>
#include <malloc.h>
typedef struct Link{
Link *next;
int data;
}link;
link* createLink()
{
link *head,*p,*s;
head=(link*)malloc(sizeof(link));
p=head;
int cycle=1;
int a=0;
while(cycle)
{
printf("please input the data\n");
scanf("%d",&a);
if(a!=0)
{
s=(link*)malloc(sizeof(link));
s->data=a;
p->next=s;
p=s;
}
else
cycle=0;
}
head=head->next;
p->next=NULL;
return head;
}
int linkLen(link *head)
{
if(head==NULL)
return 0;
int count=0;
while(head!=NULL)
{
count++;
head=head->next;
}
return count;
}
link* linkDel(int a,link *head)//删除
{
if(head==NULL)
return NULL;
link *tmp=head->next;
link *res=head;
if(head->data==a)
return tmp;
while(tmp!=NULL)
{
if(tmp->data==a)
res->next=tmp->next;
res=res->next;
tmp=tmp->next;
}
return head;
}
link* insertLink(link *head,int a)//插入
{
link *p=(link*)malloc(sizeof(link));
p->data=a;
link *pre,*last;
pre=head;
while(a>pre->data&&pre->next!=NULL)
{
last=pre;
pre=pre->next;
}
if(a<=pre->data)
{
if(head==pre)//insert before the head
{
p->next=pre;
head=p;
}
else//in the middle of link
{
last->next=p;
p->next=pre;
}
}
else//at the end of the link
{
pre->next=p;
p->next=NULL;
}
return head;
}
link* reverse(link *head)//反转
{
link *pre,*temp;
pre=NULL;
if(head==NULL||head->next==NULL)
return head;
while(head->next!=NULL)
{
temp=head->next;
head->next=pre;
pre=head;
head=temp;
}
head->next=pre;
return head;
}
void linkPrintf(link *head)
{
int len=linkLen(head);
while(len--)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}
int main()
{
link *head;
head=createLink();
linkPrintf(head);
head=insertLink(head,4);
linkPrintf(head);
head=linkDel(4,head);
linkPrintf(head);
head=reverse(head);
linkPrintf(head);
int n=linkLen(head);
printf("%d\n",n);
}
单链表的基本操作
最新推荐文章于 2023-08-16 17:51:34 发布