链表
LinkList.h
#ifndef LINKLIST_H
#define LINKLIST_H
#include <stdlib.h>
#define SUCCESS 10000
#define FAILURE 10001
typedef int ElemType;
struct Node
{
ElemType data;
struct Node *next;
};
typedef struct Node Link;
typedef Link * pLink;
int InitLink(pLink *l);
int InsertLink(pLink l,int p,ElemType e);
int TraverseLink(pLink l,void (*p)(ElemType));
#endif
LinkList.c
include "LinkList.h"
int InitLink(pLink *l)
{
if (NULL == l)
{
return FAILURE;
}
*l = (pLink)malloc(sizeof(Link) * 1);
if (NULL == (*l))
{
return FAILURE;
}
(*l)->next = NULL;
return SUCCESS;
}
int InsertLink(pLink l,int p,ElemType e)
{
if (NULL == l)
{
return FAILURE;
}
int k = 1;
pLink q = l;
while (k<p && q)
{
k++;
q = q->next;
}
if (!q||p <=0)
{
return FAILURE;
}
pLink n = (pLink)malloc(sizeof(Link) * 1);
if (NULL == n)
{
return FAILURE;
}
n->data = e;
n->next = q->next;
q->next = n;
return SUCCESS;
}
int TraverseLink(pLink l,void (*p)(ElemType))
{
if (NULL == l)
{
return FAILURE;
}
pLink n = l->next;
while (n)
{
p(n->data);
n = n->next;
}
return SUCCESS;
}
main.c
#include <stdio.h>
#include “LinkList.h”
#include <time.h>
void print(ElemType e)
{
printf("%d ",e);
}
int main()
{
pLink link;
int ret, i;
ElemType e;
srand(time(NULL));
ret = InitLink(&link);
if (SUCCESS == ret)
{
printf("Init Success!\n");
}
else
{
printf("Init Failure!\n");
}
for (i = 0;i < 10;i++)
{
e = rand() % 20;
ret = InsertLink(link, 1,e);
if (SUCCESS == ret)
{
printf("Insert %d Success!\n",e);
}
else
{
printf("Insert Failure!\n");
}
}
ret = TraverseLink(link, print);
if (ret == FAILURE)
{
printf("Traverse Failure!\n");
}
else
{
printf("Traverse Success!\n");
}
return 0;
}