#ifndef _LINKLIST_H
#define _LINKLIST_H
#define FAILURE 10000
#define SUCCESS 10001
#define TRUE 10002
#define FALSE 10003
typedef int ElemType;
struct node
{
ElemType data; //数据域
struct node *next; //指针域
};
typedef struct node Node;
#endif
#include <stdio.h>
#include <stdlib.h>
int LinkInit(Node **l) //初始化
{
*l=(Node *)malloc(sizeof(Node)*1);
if(NULL == *l)
{
return FAILURE;
}
(*l)->next=NULL;
return SUCCESS;
}
/*
int LinkInsert(Node *l,ElemType e) //头插法
{
Node *p=l;
if(NULL == l)
{
return FAILURE;
}
Node *q = (Node *)malloc(sizeof(Node)*1); //要插入的
q->data=e;
Node *t = p->next;
p->next = q;
q->next = t;
}
*/
int LinkInsert(Node *l,ElemType e) //头插法
{
Node *p=l;
int k=1;
if(NULL == l)
{
return FAILURE;
}
Node *q=(Node *)malloc(sizeof(Node)*1); //要插入的
while(k < 1 || p == NULL)
{
p = p->next;
k++;
}
if(k > 1 || p == NULL)
{
return FAILURE;
}
if(NULL == q)
{
return FAILURE;
}
q->data = e;
Node *t = p->next;
p->next = q;
q->next = t;
}
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;
}
void print(ElemType e)
{
printf("%d ", e);
}
int main()
{
int ret, i;
srand(time(NULL));
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 = LinkInsert(first, rand() % 20);
if (ret == FAILURE)
{
printf("Insert Failure!\n");
}
else
{
printf("Insert Success!\n");
}
}
ret = LinkTraverse(first, print);
if (ret == FAILURE)
{
printf("\nTraverse Falure!\n");
}
else
{
printf("\nTraverse Success!\n");
}
return 0;
}
头插法:
尾插法: