为了简化算法,可以在单链表的头结点之前增加一个表头结点
表头结点的数据域中并不存放线性表中的数据元素
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
#define Overflow 2
#define Underflow 3
#define NotPresent 4
#define Duplicate 5
typedef int Status;
//带表头结点的单链表的定义
typedef int ElemType;
typedef struct node
{
ElemType element;
struct node *link;
}Node;
typedef struct headerList
{
Node *head;
int n;
} HeaderList;
//带表头结点的单链表的初始化
Status Init(HeaderList *h)
{
h->head = (Node*)malloc(sizeof(Node));
if(!h->head) return ERROR;
h->head->link = NULL;
h->n = 0;
return OK;
}
//带表头结点的单链表的查找
Status Find(HeaderList h,int i,ElemType *x)
{
Node *p;
int j;
if(i<0 || h.n-1)
return ERROR;
p = h.head;
for(j=0;j<i;j++)
p=p->link;
*x = p->element;
return OK;
}
//带表头结点的单链表的插入运算
Status Insert(HeaderList *h,int i,ElemType x)
{
Node *p,*q;
int j;
if (i<-1 || i>h->n-1)
return ERROR;
p = h->head;
for(j=0;j<i;j++)
{
p = p->link;
}
q = (Node*)malloc(sizeof(Node));
q->element = x;
q->link = p->link;
p->link = q;
h->n++;
return OK;
}
//带表头结点的单链表的删除
Status Delete(HeaderList *h,int i)
{
int j;
Node *p,*q;
if(!h->n)
return ERROR;
if(i<0 || i>h->n-1)
return ERROR;
q = h->head;
for(j=0;j<i-1;j++)
q = q->link;
p = q->link;
q->link = p->link;
free(p);
h->n--;
return OK;
}
//单链表的输出
Status Output(headerList *h)
{
Node *p;
if (!h->n) return ERROR;
p = h->head;
while(p)
{
printf("%d ",p->element);
p = p->link;
}
printf("\n");
return OK;
}
//带表头结点的单链表的撤销
void Destroy(HeaderList *h)
{
Node *p;
while(h->head)
{
p = h->head->link;
free(h->head);
h->head = p;
}
}
int main(void)
{
int i,x;
HeaderList list;
Init(&list);
for(i=0;i<9;i++)
Insert(&list,i-1,i);
printf("Insert-->The LinkList is:");
Output(&list);
Delete(&list,2);
printf("Delete-->The LinkList is:");
Output(&list);
Find(list,5,&x);
printf("the find value is:%d ",x);
Destroy(&list);
return 0;
}