#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node {
int data;
struct Node *next;
}Node, *LinkList;
int CreateListHead(LinkList *L, int n)
{
LinkList p;
int i;
srand(time(0));
(*L) = (LinkList)malloc(sizeof(Node));
if((*L) == NULL)
{
return -1;
}
(*L)->next = NULL;
for(i = 0; i < n; i++)
{
p = (LinkList)malloc(sizeof(Node));
if(p == NULL)
{
return -1;
}
p->data = rand()%100 + 1;
p->next = (*L)->next;
(*L)->next = p;
}
return 0;
}
int CreateListTail(LinkList *L, int n)
{
LinkList p, r;
int i;
srand(time(0));
(*L) = (LinkList)malloc(sizeof(Node));
if((*L) == NULL)
{
return -1;
}
r = (*L);
for(i = 0; i < n; i++)
{
p = (LinkList)malloc(sizeof(Node));
if(p == NULL)
{
return -1;
}
p->data = rand()%100 + 1;
r->next = p;
r = p;
}
r->next = NULL;
return 0;
}
int ListInsert(LinkList *L, int i, int e)
{
LinkList p = *L, s;
int j = 1;
while(p && j < i)
{
p = p->next;
++j;
}
if(!p || j > i)
{
return -1;
}
s = (LinkList)malloc(sizeof(Node));
if(s == NULL)
{
return -1;
}
s->data = e;
s->next = p->next;
p->next = s;
return 0;
}
int ListDel(LinkList *L, int i, int *e)
{
LinkList p = *L, q;
int j = 1;
while((p->next) && j < i)
{
p = p->next;
++j;
}
if(!p ||j > i)
{
return -1;
}
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return 0;
}
int DestoryList(LinkList *L)
{
LinkList q, p = (*L)->next;
int i = 0;
printf("\n");
while(p)
{
q = p->next;
printf("[Destory list] Free %dth element %d.\n", ++i, p->data);
free(p);
p = q;
}
return 0;
}
void PrintList(LinkList L)
{
LinkList p = L->next;
int i = 0;
while(p)
{
printf("[Print list] %dth element %d. \n",++i, p->data);
p = p->next;
}
}
int TestCaseForList(LinkList *L, int size, int flag)
{
int ret;
if (flag == 0)
{
printf("[Test case for list] falg == 0.\n");
ret = CreateListTail(L, size);
if(ret == 0)
{
printf("[Test case for list] sucess.\n\n");
}
else
{
return -1;
}
}
else
{
printf("[Test case for list] falg == 1.\n");
ret = CreateListHead(L, size);
if(ret == 0)
{
printf("[Test case for list] sucess.\n");
}
else
{
return -1;
}
}
PrintList(*L);
ret = ListInsert(L, 1, 25000);
if(ret == -1)
{
return -1;
}
printf("\n[Test case for list] Insert after.\n");
PrintList(*L);
int val = 0;
ret = ListDel(L, 1, &val);
if(ret == -1)
{
return -1;
}
printf("\n[Test case for list] Del element %d.\n", val);
PrintList(*L);
ret = DestoryList(L);
if(ret != 0)
{
return -1;
}
return 0;
}
int main(void)
{
LinkList *L;
int size = 10, flag = 1;
int ret = TestCaseForList(L, size, flag);
if(ret == -1)
{
printf("[Main] failed.\n");
return -1;
}
return 0;
}
《大话数据结构》 程杰