线性表结构之单链表

//initial linklist
Status LinkListInit(LinkList *L)
{
	*L = (LinkList)malloc(sizeof(Node)); /* 产生头结点,并使L指向此头结点 */
	if (!*L)
		return ERROR;
	(*L)->next = NULL;
	return OK;
}
//get element 
Status LinkListGetElem(LinkList L, int i, ElemType *e)//L为头指针
{
	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;
}
//insert element
Status LinkListInsert(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 = (Node *)malloc(sizeof(Node));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return OK;
}
Status InsertL(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 = (Node *)malloc(sizeof(Node));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return OK;
}
//delete element
Status LinkListDelete(LinkList *L, int i, ElemType *e)
{
	int j;
	LinkList p, q;
	p = *L;
	j = 1;
	while (p->next&&j < i)
	{
		p = p->next;
		++j;
	}
	if (!(p->next) || j>i)
		return ERROR;
	q = p->next;
	*e = q->data;
	p->next = q->next;
	free(q);
	return OK;
}

//create linklist
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 = (Node *)malloc(sizeof(Node));
		p->data = rand()%100 + 1;
		p->next = (*L)->next;
		(*L)->next = p;//头插法
	}
}

void CreateLinkListTail(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;
}

你可能感兴趣的:(线性表结构之单链表)