|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct lianbiao
{
int shujuyu;
struct lianbiao * zhizhenyu;
}NODE, *PNODE;
PNODE chuangjian(void);
void shuchu(PNODE To);
int changdu(PNODE To);
void paixu(PNODE To);
bool charu(PNODE To, int pos, int val);
bool shanchu(PNODE To, int pos,int * pVal);
int main(void)
{
int val = 0;
PNODE To = NULL;
To = chuangjian();
shuchu(To);
int len = changdu(To);
printf("链表的长度为:%d\n", len);
paixu(To);
shuchu(To);
if ( charu(To, 3, 10) )
{
printf("插入成功,自动为您遍历当前链表!\n");
shuchu(To);
}
else
{
printf("插入失败,自动为您遍历当前链表!\n");
shuchu(To);
}
if ( shanchu(To, 3, &val) )
{
printf("删除成功,您删除的值是%d,自动为您遍历当前链表!\n", val);
shuchu(To);
}
else
{
printf("删除失败,您删除的节点不存在,自动为您遍历当前链表!\n");
shuchu(To);
}
return 0;
}
PNODE chuangjian(void)
{
int len = 0;
int i, val;
PNODE To = (PNODE) malloc (sizeof(NODE));
if (NULL == To)
{
printf("动态内存分配失败,程序终止!\n");
exit(-1);
}
printf("请输入链表的长度:");
scanf("%d", &len);
PNODE Wei = To;
To->zhizhenyu = NULL;
for (i=0; i<len; ++i)
{
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &val);
PNODE Xin = (PNODE) malloc (sizeof(NODE));
if (NULL == To)
{
printf("动态内存分配失败,程序终止!\n");
exit(-1);
}
Xin->shujuyu = val;
Xin->zhizhenyu = NULL;
Wei->zhizhenyu = Xin;
Wei = Xin;
}
return To;
}
void shuchu(PNODE To)
{
PNODE p = To->zhizhenyu;
while (NULL != p)
{
printf("%d ", p->shujuyu);
p = p->zhizhenyu;
}
printf("\n");
return;
}
int changdu(PNODE To)
{
PNODE p = To->zhizhenyu;
int len = 0;
while (NULL != p)
{
p = p->zhizhenyu;
len++;
}
return len;
}
void paixu(PNODE To)
{
int len = ( changdu(To) );
PNODE p, q;
int i, j, t;
for (i=0,p=To->zhizhenyu; i<len-1; ++i,p=p->zhizhenyu)
{
for(j=i+1,q=p->zhizhenyu; j<len; ++j,q=q->zhizhenyu)
{
if (p->shujuyu > q->shujuyu)
{
t = p->shujuyu;
p->shujuyu = q->shujuyu;
q->shujuyu = t;
}
}
}
return;
}
bool charu(PNODE To, int pos, int val)
{
int i = 0;
PNODE p = To;
while (p!=NULL && i<pos-1)
{
p = p->zhizhenyu;
++i;
}
if (i>pos-1 || NULL==p)
return false;
PNODE Xin = (PNODE) malloc (sizeof(NODE));
if (NULL == Xin)
{
printf("动态内存分配失败,程序终止!\n");
exit(-1);
}
Xin->shujuyu = val;
Xin->zhizhenyu = NULL;
PNODE q = p->zhizhenyu;
p->zhizhenyu = Xin;
Xin->zhizhenyu = q;
return true;
}
bool shanchu(PNODE To, int pos, int * pVal)
{
int i = 0;
PNODE p = To;
while (To->zhizhenyu!=NULL && i<pos-1)
{
p = p->zhizhenyu;
++i;
}
if (i>pos-1 || p->zhizhenyu==NULL)
return false;
PNODE q = p->zhizhenyu;
*pVal = q->shujuyu;
p->zhizhenyu = p->zhizhenyu->zhizhenyu;
free(q);
q = NULL;
return true;
}
|
|