#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(DataList_t)
#define N 10
typedef struct tagDataList_t
{
int Data;
struct tagDataList_t *next;
}DataList_t;
DataList_t * CreatList(int a[]);
void Print(DataList_t *pHead);
int Sereach(DataList_t * pHead,int n);
void Delete(DataList_t **pHead,int location);
void Insert(DataList_t **pHead,int location, int a[]);
void Reverse(DataList_t **pHead);
void Free(DataList_t * pHead);
void main(int argc, char *argv[])
{
DataList_t *pHead;
int a[N]={4,8,7,4,4,45,5,7,74,9};
int location,number;
pHead=CreatList(a);
Print(pHead);
printf("输入要查询的数字:");
scanf("%d",&number);
location=Sereach(pHead,number);
if (location!=11)
{
printf("/n元素在链表的第%d个结点处/n",location);
}
else
{
printf("/n所查数字不在其中/n");
}
Delete(&pHead,location);
Insert(&pHead,location,a);
Print(pHead);
Reverse(&pHead);
Print(pHead);
Free(pHead);
}
DataList_t * CreatList(int a[])
{
DataList_t *pHead = NULL, *p = NULL, *q = NULL;
int i;
if ((pHead = (DataList_t *)malloc(LEN))==NULL)
{
exit(1);
}
pHead->Data = a[0];
pHead->next=NULL;
q = pHead;
for(i=1;i<N;i++)
{
p = (DataList_t *)malloc(LEN);
p->Data=a[i];
p->next=q->next;
q->next=p;
q=p;
}
return pHead;
}
void Print(DataList_t * pHead)
{
DataList_t *p;
assert(pHead!=NULL);
printf("pHead");
p=pHead;
for(; p!=NULL; p=p->next)
{
printf("->%d",p->Data);
}
printf("/n");
}
void Delete(DataList_t **pHead,int location)
{
DataList_t *p,*q;
int i;
p=*pHead;
if (location==1)
{
*pHead = (*pHead)->next;//这样可以改变主函数的头结点
free(p);
return ;
}
else if(location>=11)
{
return ;
}
else
{
for(i=1; i<location-1; i++,p=p->next);
q=p->next;
p->next=p->next->next;
free(q);
}
}
int Sereach(DataList_t * pHead,int n)
{
DataList_t *p;
int i=1;
assert(pHead!=NULL);
p=pHead;
while(p)
{
if(p->Data!=n)
{
p=p->next;
i++;
}
else
{
break;
}
}
return i;
}
void Insert(DataList_t **pHead,int location, int a[])
{
int i;
DataList_t *p,*q;
p = *pHead;
if((q=(DataList_t *)malloc(LEN))==NULL)
{
exit(1);
}
if(location!=10)
{
q->Data=a[location];
q->next=NULL;
}
else
{
q->Data=a[location-1];
q->next=NULL;
}
if(location==1)
{
q->next=*pHead;
*pHead=q;
}
else if(location!=11&&location !=10)
{
for(i=1; i<location; i++,p=p->next);
q->next=p->next;
p->next=q;
}
else if(location==10)
{
for(i=1; i<location-1; i++,p=p->next);
p->next=q;
}
}
void Reverse(DataList_t **pHead)
{
DataList_t *p, *q, *m;
p = *pHead;
m = p;
p = p->next;
m->next = NULL;
while(p->next!=NULL)
{
q = p;
p = p->next;
q->next = m;
m = q;
}
p->next = q;
*pHead = p;
}
void Free(DataList_t * pHead)
{
DataList_t *p;
p=pHead->next;
while (p)
{
pHead->next = p->next;
free(p);
p=pHead->next;
}
printf("/n释放成功!/n");
}