带表头结点的单链表

为了简化算法,可以在单链表的头结点之前增加一个表头结点
表头结点的数据域中并不存放线性表中的数据元素

#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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值