不设头结点的单链表
不设头结点的单链表插入和删除第一个元素时需要改变链表头指针的值,所以需要二级指针。
typedef int ElemType;
struct Node
{
ElemType data;
struct Node * pNext;
};
//不设头结点的单链表的基本操作(9个)
//1构造一个空的链表
struct Node * init_list()
{
struct Node * pHead;
pHead = (struct Node *)malloc(sizeof(struct Node));
if (!pHead)
exit(-1);
pHead = NULL;
return pHead;
}
//2将链表置为空
void clear_list(struct Node * pHead)
{
struct Node * p;
while (pHead)
{
p = pHead;
pHead = pHead->pNext;
free(p);
}
}
//3判断是否为空
bool is_empty(struct Node * pHead)
{
if (pHead == NULL)
return true;
else
return false;
}
//4返回链表中元素个数
int length_list(struct Node * pHead)
{
if (is_empty(pHead))
return 0;
else
{
int cnt = 0;
struct Node * p;
p = pHead;
while (NULL != p)
{
cnt++;
p = p->pNext;
}
return cnt;
}
}
//5取得第pos个位置上元素的值
bool get_list(struct Node * pHead, int pos, ElemType * value)
{
int i = 0;
struct Node * p = pHead;
while (p && i < pos - 1)
{
i++;
p = p->pNext;
}
if (!p || i > pos - 1)
return false;
*value = p->data;
return true;
}
//6给定一个数,得到线性表中与此数相等的最小的位序
bool compare(ElemType e1, ElemType e2)
{
if (e1 == e2)
return true;
else
return false;
}
int locate_list(struct Node * pHead, ElemType val)
{
int i = 0;
struct Node * p = pHead;
while (p)
{
i++;
if(compare(p->data, val))
return i;
p = p->pNext;
}
return 0;
}
//7插入数据
bool insert_list(struct Node ** pHead, int pos, int value)
{
int i = 1;
struct Node * p = *pHead;
if (pos < 1)
return false;
struct Node * pNew = (struct Node *) malloc(sizeof (struct Node));
pNew->data = value;
if (pos == 1)
{
pNew->pNext = *pHead;
*pHead = pNew;
}
else
{
while (p && i < pos - 1)
{
p = p->pNext;
i++;
}
if (!p)
return false;
struct Node * q = p->pNext;
pNew->pNext = q;
p->pNext = pNew;
}
return true;
}
//8删除数据
bool delete_list(struct Node ** pHead, int pos, int * val)
{
int i = 1;
struct Node * p = *pHead;
struct Node * q;
if (!*pHead)
return false;
else if (pos == 1)
{
*pHead = p->pNext;
*val = p->data;
free(p);
}
else
{
while (p->pNext && i < pos - 1)
{
i++;
p = p->pNext;
}
if (!p->pNext || i > pos - 1)
return false;
q = p->pNext;
p->pNext = q->pNext;
*val = q->data;
free(q);
}
return true;
}
//9遍历链表
void traverse_list(struct Node * pHead)
{
struct Node * p = pHead;
while (p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
//10给定一个数,判断是否在链表里,如果在,从第二个元素开始得到此数的前一个数
bool prior_list(struct Node * pHead, ElemType cur_e, ElemType * pre_e)
{
struct Node * q;
struct Node * p = pHead;
while (p->pNext)
{
q = p->pNext;
if (q->data == cur_e)
{
*pre_e = p->data;
return true;
}
p = q;
}
return false;
}
//11返回cur的后一个
bool next_list(struct Node * pHead, ElemType cur_e, ElemType * next_e)
{
struct Node * p = pHead;
while (p->pNext)
{
if (p->data == cur_e)
{
*next_e = p->pNext->data;
return true;
}
p = p->pNext;
}
return false;
}