《大话数据结构》之单链表

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int Status;
typedef int ElemType;

#define MAXSIZE 20
typedef struct 
{
	ElemType data [MAXSIZE];
	int length;
}SqList;

typedef struct Node
{
	ElemType data;
	struct Node *next;
};

typedef struct Node *LinkList;

//用e返回L中第i个数据元素的值
Status GetElem(LinkList L,int i,ElemType *e)
{
	int j;
	LinkList p;
	p= L->next;
	j = 1;
	while(p && j<i)
	{
		p = p->next;
		++j;
	}
	if(!p || j > i)
	{
		return ERROR;
	}
	*e = p->data;
	return OK;
}

//在L中第i个节点位置之前插入新的数据元素e,L的长度增加1
Status ListInsert(LinkList L,int i,ElemType e)
{
	int j;
	LinkList p,s;
	p = L;
	j = 1;
	while(p && j < i)
	{
		p = p->next;
		++j;
	}
	if(!p || j > i)
	{
		return ERROR;
	}
	s = (LinkList)malloc(sizeof(Node));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return OK;
}

//删除L的第i个节点,并用e返回其值,L的长度减一
Status ListDelete(LinkeList L,int i,ElemType e)
{
	int j;
	LinkList p,q;
	p = L;
	j = l;
	while(p->next && j < i)
	{
		p = p->next;
		++j;
	}
	if(!(p-next) || j > i)
	{
		return ERROR;
	}
	q = p->next;
	p->next = q->next;
	*e = q->data;
	free(q);
	return OK;
}

//随机产生n个元素的值,建立带有表头节点的单链线性表L(新增节点插在表头)
void CreateListHead(LinkList L,int n)
{
	LinkList p;
	int i;
	srand(time(0));
	L = (Node *)malloc(sizeof(Node));
	L->next = NULL;
	for(i=0;i<n;i++)
	{
		p = (LinkList)malloc(sizeof(Node));
		p->data = rand()%100 + 1;
		p->next = L->next;
		L->next = p;
	}
}

//随机产生n个元素的值,建立带表头节点的单链线性表L(新增节点插在链表尾部)
void CreateListTail(LinkList L,int n)
{
	LinkList p,r;
	int i;
	srand(time(0));
	L = (LinkList)malloc(sizeof(Node));
	r = L;
	for(i=0;i<n;i++)
	{
		p =(Node *)malloc(sizeof(Node));
		p->data = rand()%100 + 1;
		r->next = p;
		r = p;
	}
	r->next = NULL;
}

//清空单链表,从表头开始,单保留头结点
Status ClearList(LinkList L)
{
	LinkList p,q;
	p = L->next;
	while(p)
	{
		q = p->next;
		free(p);
		p=q;
	}
	L->next = NULL;
	return OK;
}

你可能感兴趣的:(数据结构,单链表,大话数据结构)