单链表的C语言算法实现
自己用C语言实现的单链表算法,有什么不正确的地方,请各位共同讨论与指正。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
int data; //结点数据域
struct Node *pNext; //指向下一结点的指针域
}NODE, *PNODE;
//创建一个链表
PNODE create_list(void)
{
PNODE pHead; //链表头指针
PNODE pTail; //链表尾指针
int length; //链表有效结点个数
int i;
int val; //每个结点的数据域
PNODE pNew; //指向新创建的结点
printf("请输入要创建链表结点的个数:length= ");
scanf("%d", &length);
pHead = (PNODE)malloc(sizeof(NODE)); //创建头结点
if (pHead == NULL)
{
printf("内存分配失败,程序将终止!\n");
exit(-1);
}
pHead->pNext = NULL;
pTail = pHead; //链表有效结点为零时,尾结点相当于头结点
for (i=0; i<length; i++)
{
printf("请输入第%d个结点的值:", i+1);
scanf("%d", &val);
pNew = (PNODE)malloc(sizeof(NODE)); //为新结点分配内存
if (pNew == NULL)
{
printf("内存分配失败,程序将终止!\n");
exit(-1);
}
pNew->data = val;
pTail->pNext = pNew; //使尾结点的指针域指向新创建的结点
pNew->pNext = NULL; //使新创建结点的指针域指向NULL
pTail = pNew; //把新创建的结点变成尾结点
}
return pHead;
}
//遍历整个链表
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while (p != NULL)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
//判断链表是否为空
int is_empty(PNODE pHead)
{
if (pHead->pNext == NULL)
{
return 0;
}
else
{
return -1;
}
}
//求链表的长度
int length_list(PNODE pHead)
{
int length = 0;
PNODE p = pHead->pNext;
while (p != NULL)
{
length++;
p = p->pNext;
}
return length;
}
//排序
void sort_list(PNODE pHead)
{
int i, j, t, len = length_list(pHead);
PNODE p, q;
p = pHead;
for (i=0; i<len-1; i++)
{
p = p->pNext;
q = p->pNext;
for (j=i+1; j<len; j++)
{
if (p->data > q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
q = q->pNext;
}
}
}
//在第pos个结点之前插入一个结点val
int insert_list(PNODE pHead, int pos, int val)
{
PNODE p = pHead;
int i=0;
while (p != NULL && i < pos - 1)
{
p = p->pNext;
i++; //找到第i个结点
}
if (p == NULL || i > pos - 1)
{
return -1;
}
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (pNew == NULL)
{
printf("内存分配失败,程序将终止!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = p->pNext;
p->pNext = pNew;
return 0;
}
//删除第pos个结点
int delete_list(PNODE pHead, int pos, int *pVal)
{
PNODE p = pHead;
int i=0;
//找到待删结点的前一个结点
while (p->pNext != NULL && i < pos - 1)
{
p = p->pNext;
i++;
}
if (p->pNext == NULL || i > pos - 1)
{
return -1;
}
*pVal = p->pNext->data;
PNODE q = p->pNext;
p->pNext = p->pNext->pNext;
free(q);
return 0;
}
int main()
{
int val;
PNODE pHead = create_list();
traverse_list(pHead);
if (delete_list(pHead, 3, &val) == 0)
{
printf("删除成功,您删除的元素是:%d\n", val);
}
else
{
printf("删除失败\n");
}
traverse_list(pHead);
return 0;
}
网友评论