一、存储结构
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
二、基本操作
1、初始化
//创建只含头结点的空链表
int InitList(LNode *&L)
{
L = (LNode *)malloc(sizeof(LNode));
if (NULL == L)
{
printf("Memory allocate failed\n");
return 0;
}
L->next = NULL;
//L->data = 0;
return 1;
}
2、销毁单链表
void DestoryList(LNode *&L)
{
//LNode *p;
//while(L)
//{
// p = L;
// L = L->next;
// free(p);
//}
LNode*p, *q;
p = L;
while(NULL != p)
{
q = p->next;
free(p);
p = q;
}
L = NULL;
}
3、将单链表置为空表
void ClearList(LNode *&L)
{
DestoryList(L->next);
//LNode *p, *q;
//p = L->next;
//while (p)
//{
// q = p->next;
// free(p);
// p = q;
//}
L->next = NULL;
}
4、指定位置插入元素
//在带头结点的单链线性表L中的第i个位置之前插入元素e
//1<= i <=(链表长+1)
int ListInsert(LNode *&L, int i, int e)
{
LNode *p, *s;
//寻找第i-1个位置
p= L;
int j = 1;
while(p && j < i )
{
p = p->next;
j++;
}
if (!p || j > i)//i<1 or i>(表长+1)
return 0;
s = (LNode*)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;//插入
p->next = s;
return 1;
}
5、指定位置删除元素
//在带头结点的单链线性表L中,删除第i个位置的元素,并用e返回其值
//1<=i<=链表长
int ListDelete(LNode *&L, int i, int &e)
{
LNode *p, *q;
//寻找第i个结点,并令p指向其前驱
p= L;
int j = 1;
while(p->next && j < i)
{
p = p->next;
j++;
}
if(!(p->next) || j > i)
return 0;//删除位置不合理
q = p->next;//待删除的结点
e = q->data;
p->next = q->next;
free(q);
return 1;
}
6、获取单链表第i个节点的值
int GetElem(LNode*L, int i, int &e)
{
LNode *p = L->next;//p指向首元结点
int j = 1;
while(p && j < i)
{
p = p->next;
j++;
}
if(!p || j > i)
return 0;
e = p->data;
return 1;
}
7、查找值域为e的节点在单链表中的位置
int LocateElem(LNode*L, int e)
{
LNode *p = L->next;
int i = 0;
while(p)
{
i++;
if(p->data == e)
return i;
p = p->next;
}
return 0;
}
8、遍历单链表
void ListTraverse(LNode*L)
{
LNode*p = L->next;
while(p)
{
printf("->%d", p->data);
p = p->next;
}
putchar('\n');
}
9、获取单链表的长度
int ListLength(LNode *L)
{
int i = 0;
LNode *p = L->next;//首元结点
while(p)
{
i++;
p = p->next;
}
return i;
}
接下篇:数据结构之单链表(二)