链表是一个存储非连续数据的线性结构,它与顺序表想比其不会浪费过多的空间,实现了不连续的存储
先做预备操作
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* pNext;
}NODE,*PNODE;
int main()
{
PNODE pHead = creatlist();
}
接下来便要创造一个空的链表
PNODE creatlist()
{
int len;//节点数
int val;//暂时存放数据
printf("请输入存放的节点的个数:");
scanf("%d", &len);
PNODE pHead = (PNODE)malloc(szieof(NODE) * len);
if (NULL == pHead)
{
printf("内存分配失败!\n");
exit(-1);
}
PNODE pTail = pHead->pNext;
pTail->pNext = NULL;//防止用户输入的节点个数为0
for (int i = 0; i < len; i++)
{
printf("请输入第%d个节点的数据", i + 1);
scanf("%d", &val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
创建完毕后,我们看下遍历程序
void traverselist(PNODE pHead)
{
PNODE p = pHead->pNext;
while (p != NULL)
{
printf("%d ", p->data);
p = p->pNext;
}
}
判断链表是否为空
bool emptylist(PNODE pHead)
{
if (pHead->pNext== NULL)
return true;
else
return false;
}
判断链表的长度
int lengthlist(PNODE pHead)
{
int cnt;
PNODE p = pHead->pNext;
while (p->pNext != NULL)
{
cnt++;
p = p->pNext;
}
return cnt;
}
接下来我们可以对于链表中存储的元素进行按照一定的顺序来进行排列
void sortlist(PNODE pHead)
{
PNODE p=NULL;
PNODE q = NULL;
int tem;
int len = lenghtlist(pHead);
for (int i = 0,p=pHead->pNext; i < len; i++,p=p->pNext)
{
for (int j = 0,q=p->pNext; j < len - 1 - i; j++,q=p->pNext)
{
if (p->data < q->data)
{
tem = p->data;
p->data = q->data;
q->data = tem;
}
}
}
}
我们可以对链表进行插入元素的处理
bool insert(PNODE pHead, int pos, int val)
{
int i = 0;
PNODE p=pHead;
while (i < pos - 1 && p != NULL)
{
i++;
p = p->pNext;
}
//此时,pos-1位置是p
if (i > pos - 1 || p == NULL)
return false;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("内存分配失败!\n");
exit(-1);
}
pNew->data = val;
PNODE r = p->pNext;
p->pNext = pNew;
pNew->pNext = r;
return true;
}
我们也可以对其进行删除处理
bool deletelist(PNODE pHead, int pos, int* pVal)
{
int i = 0;
PNODE p = pHead;
while (i < pos - 1 && p != NULL)
{
p = p->pNext;
i++;
}
if (i > pos - 1 || p == NULL)
{
printf("内存分配失败!\n");
exit(-1);
}
PNODE q = p->pNext;
*pVal = q->data;
p->pNext = q->pNext;
free(q);
q = NULL;
return true;
}
做完处理后我们可以清除链表,使其变为一个空链表
bool clearlist(PNODE pHead)
{
if (emptylist(pHead))
return false;
else
{
PNODE p = pHead->pNext;
while (p != NULL)
{
PNODE q = p->pNext;
p->pNext = q->pNext;
free(q);
p = p->pNext;
return true;
}
}
}
我们甚至可以销毁一个链表
void destorylist(PNODE pHead)
{
if (pHead == NULL)
printf("over");
else
{
PNODE p = pHead->pNext;
while (p != NULL)
{
free(pHead);
pHead = p;
p = p->pNext;
}
}
}
我们还可以查找链表中有无所需的特定值
void findlist(PNODE pHead, int val)
{
int cnt = 0;
PNODE p = pHead->pNext;
for (int i = 0; i < lengthlist(pHead))
{
if (val == p->data)
printf("Find it!\n");
p = p->pNext;
}
}