初学链表,相互交流
#include <stdio.h>
#include <stdlib.h>
typedef struct data data;
struct data
{
int value;
data* pnext;
data* plast;
};
data* create(int n);
void insert(data* head);
void reverse(data* head);
void print(data*head);
int mid(data* head);
void pfree(data* head);
int main(void)
{
int n=5;
data* head=NULL;
head=create(n);
insert(head);
reverse(head);
int zhong=mid(head);
printf("mid_value=%d\n",zhong);
print(head);
pfree(head);
return 0;
}
data* create(int n)
{
data *head=NULL,*p=NULL,*l=NULL;
for(int i=0;i<=n;i++)
{
if(i==0){
p=(data*)malloc(sizeof(data));
head=p;
head->plast=NULL;
}
else{
p=(data*)malloc(sizeof(data));
l->pnext=p;
p->plast=l;
printf("输入第%d个数:",i);
scanf("%d",&p->value);
}
l=p;
p->pnext=NULL;
}
return head;
}
void insert(data* head)
{
int new_value;
printf("Input the new_value:");
scanf("%d",&new_value);
data *pcurrent=NULL,*p=NULL,*temp=NULL;
pcurrent=head->pnext;
p=(data*)malloc(sizeof(data));
p->value=new_value;
if(new_value<head->pnext->value)//小于第一个节点
{
temp=head->pnext;
head->pnext=p;
p->pnext=temp;
return;
}
while(pcurrent!=NULL&&pcurrent->value<new_value)
{
temp=pcurrent;
pcurrent=pcurrent->pnext;
}
if(pcurrent!=NULL){//在中间插入
p->pnext=pcurrent;
pcurrent->plast=p;
}
else{//在结尾插入
p->pnext=NULL;
}
//必执行的代码
temp->pnext=p;
p->plast=temp;
}
void reverse(data*head)
{
data *temp=NULL,*p=NULL;
temp=head->pnext;
head->pnext=NULL;
while(temp)
{
p=temp;
temp=temp->pnext;
p->pnext=head->pnext;
head->pnext=p;
}
}
int mid(data*head)
{
data *pmid=head,*pl=head;
while(pl&&pl->pnext)
{
pmid=pmid->pnext;
pl=pl->pnext->pnext;
}
return pmid->value;
}
void print(data* head)
{
data* p=head->pnext;
while(p)
{
printf("\t%d",p->value);
p=p->pnext;
}
}
void pfree(data* head)
{
data* p=NULL;
while(head)
{
p=head;
head=head->pnext;
free(p);
}
}