一头文件
#ifndef _SEQUENCELIST_H
#define _SEQUENCELIST_H
#define SIZE 10
#define SUCCESS 10001
#define FAILURE 10002
typedef int elemtype;
struct node
{
elemtype data; //数据域
struct node *next; //指针域
};
typedef struct node Node;
int LinkInit(Node **l);
int Headinsert(Node *l, elemtype e);
int LinkTraverse(Node *l,void(*p)(elemtype));
int Tailinsert(Node *l, elemtype e);
#endif
二 子函数
#include "LinkList.h"
#include <stdlib.h>
#include <stdio.h>
int LinkInit(Node **l)
{
*l = (Node *)malloc(sizeof(Node) * 1); //分配头结点 l 就是头指针
if (NULL == *l)
{
return FAILURE;
}
(*l)->next = NULL; //头结点指针域为
return SUCCESS;
}
int Headinsert(Node *l, elemtype e)
{
if(l == NULL)
{
return FAILURE;
}
Node *q = l;
Node *p;
p= (Node *)malloc (sizeof(Node));
p->data = e;
p->next = q->next;
q->next = p;
return SUCCESS;
}
int LinkTraverse(Node *l,void(*p)(elemtype))
{
if(NULL== l)
{
return FAILURE;
}
Node *q=l;
while(q->next)
{
q=q->next;
p(q->data);
}
return SUCCESS;
}
int Tailinsert(Node *l, elemtype e)
{
if(l==NULL)
{
return FAILURE;
}
Node *q= l;
Node *p;
p=(Node*)malloc(sizeof(Node*));
p->data=e;
p->next= NULL;
while(q->next)
{
q=q->next;
}
q->next = p;
return SUCCESS;
}
三 main函数
#include "LinkList.h"
#include <stdio.h>
void print(elemtype e)
{
printf("%d ", e);
}
int main()
{
int ret, i;
Node *first = NULL; //头指针
// srand(time(NULL));
ret = LinkInit(&first);
if (ret == FAILURE)
{
printf("Init Failure!\n");
}
else
{
printf("Init Success!\n");
}
for(i= 0;i<10;i++)
{
ret = Headinsert(first,i);
if(ret == FAILURE)
{
printf("Headinsert Failure!\n");
}
else
{
printf("Headinsert Success!\n");
}
}
ret= LinkTraverse(first, print);
if(ret==FAILURE)
{
printf("\n Traverse Failure!\n");
}
else
{
printf("\n Traverse Success!\n");
}
for(i= 0;i<10;i++)
{
ret= Tailinsert(first, i);
if(ret == FAILURE)
{
printf("Tailinsert Failure !\n");
}
else
{
printf("Tailinsert Success!\n");
}
}
ret=LinkTraverse(first,print);
{
if(ret==FAILURE)
{
printf("\n Traverse Failure!\n");
}
else
{
printf("\n Traverse Success!\n");
}
}
return 0;
}