数据结构实现单链表的基本操作

该程序在vs2013中完成!!!

单链表的基本函数:

#include
#include
typedef char ElemType;
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
} LinkList;

void InitList(LinkList *&L)
{
	L = (LinkList*)malloc(sizeof(LinkList));
	L->next = NULL;
}

void DestoryList(LinkList *&L)
{
	LinkList *p = L, *q = p->next;
	while (q != NULL)
	{
		free(p);
		p = q;
		q = p->next;
	}
	free(p);
}

int ListEmpty(LinkList *L)
{
	return(L->next == NULL);
}

int ListLength(LinkList *L)
{
	LinkList *p = L; int i = 0;
	while (p->next != NULL)
	{
		i++;
		p = p->next;
	}
	return (i);
}

void DispList(LinkList *L)
{
	LinkList *p = L->next;
	while (p != NULL)
	{
		printf("%c", p->data);
		p = p->next;
	}
	printf("\n");
}

int GetElem(LinkList *L, int i, ElemType &e)
{
	int j = 0;
	LinkList*p = L;
	while (j < i&&p != NULL)
	{
		j++;
		p = p->next;
	}
	if (p == NULL)
		return 0;
	else
	{
		e = p->data;
		return 1;
	}

}

int LocateElem(LinkList *L, ElemType e)
{
	LinkList *p = L->next;
	int n = 1;
	while (p!= NULL&&p->data != e)
	{
		p = p->next;
		n++;
	}
	if (p == NULL)
		return (0);
	else
		return(n);
}

int ListInsert(LinkList *&L, int i, ElemType e)
{
	int j = 0;
	LinkList *p = L, *s;
	while (j < i - 1 && p != NULL)
	{
		j++;
		p = p->next;
	}
	if (p == NULL)
		return 0;
	else
	{
		s = (LinkList*)malloc(sizeof(LinkList));
		s->data = e;
		s->next = p->next;
		p->next = s;
		return 1;
	}
}

int ListDelete(LinkList *&L, int i, ElemType e)
{
	int j = 0;
	LinkList *p = L, *q;
	while (j < i - 1 && p != NULL)
	{
		j++;
		p = p->next;
	}
	if (p == NULL)
		return 0;
	else
	{
		q = p->next;
		p->next = q->next;
		free(q);
		return 1;
	}
}
//在同一项目下新建main.cpp,调用上面的函数:代码如下
#include
#include
#include
typedef char ElemType;
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
} LinkList;
extern void InitList(LinkList *&L);
extern void DestoryList(LinkList *&L);
extern int ListEmpty(LinkList *L);
extern int ListLength(LinkList *L);
extern void DispList(LinkList *L);
extern int GetElem(LinkList *L, int i, ElemType &e);
extern int LocateElem(LinkList *L, ElemType e);
extern int ListInsert(LinkList *&L, int i, ElemType e);
extern int ListDelete(LinkList *&L, int i, ElemType e);
int main()
{
	LinkList *h;
	ElemType e;
	printf("(1)初始化单链表h\n");
	InitList(h);
	printf("(2)依次采用尾插入法插入a,b,c,d,e元素\n");
	ListInsert(h, 1, 'a');
	ListInsert(h, 2, 'b');
	ListInsert(h, 3, 'c');
	ListInsert(h, 4, 'd');
	ListInsert(h, 5, 'e');
	printf("(3)输出单链表h:");
	DispList(h);
	printf("(4)单链表h长度为%d\n", ListLength(h));
	printf("(5)单链表h为%s\n", (ListEmpty(h) ? "空" : "非空"));
	GetElem(h, 3, e);
	printf("(6)单链表h的第三个元素=%c\n",e);
	printf("(7)元素a的位置=%d\n",LocateElem(h,'a'));
	printf("(8)在第四个元素的位置上插入f元素\n");
	ListInsert(h,4,'f');
	printf("(9)输出单链表h:");
	DispList(h);
	printf("(10)删除h的第三个元素\n");
	ListDelete(h, 3, e);
	printf("(11)输出单链表h:");
	DispList(h);
	printf("(12)释放单链表h\n");
	DestoryList(h);

	system("pause");
	return 0;

}
数据结构实现单链表的基本操作_第1张图片

你可能感兴趣的:(数据结构)