数据结构之链表 (随便写的)

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <cstdio>

using namespace std;
typedef struct Node
{
int data;//数据域
struct Node *pnext;//指针域
}node, *pnode;//NODE 等价于struct Node pnode等价于struct Node*

pnode creat_list()
{
pnode phead = (pnode)(malloc)(sizeof(node));//头节点
if (!phead)
exit(-1);
int len;
int val;//用来存放用户输入节点的值;
printf("请输入你需要生成的链表节点的个数:len = ");
cin >> len;
pnode ptail = phead;
ptail->pnext = NULL;
for (int i = 0; i < len; i++)
{
printf("请输入第%d节点的个数的值:", i + 1);
cin >> val;
pnode pnew = (pnode)malloc(sizeof(node));
if (!pnew)
exit(-1);
pnew->data = val;
ptail->pnext = pnew;
ptail = pnew;
}
ptail-> pnext = NULL;
return phead;
}
void traverse_list(pnode phead)
{
pnode p = phead->pnext;
while (p)
{
printf("%d ", p->data);
p = p->pnext;
}
printf("\n");
return;
}
bool insert_list(pnode phead, int pos, int val)
{
int i = 0;
pnode p = phead;
while (p&& i < pos - 1)
{
p = p->pnext;
++i;
}
if (i>pos - 1 || NULL == p)
return false;
pnode pnew = (pnode)malloc(sizeof(node));
if (!pnew)
exit(-1);
pnew->data = val;
pnew->pnext = p->pnext;
p->pnext = p;
return true;
}
bool delete_list(pnode phead, int pos, int * pval)
{
int i = 0;
pnode p = phead;
while (p&& i < pos - 1)
{
p = p->pnext;
++i;
}
if (i>pos - 1 || NULL == p)
return false;
pnode q = p->pnext;
*pval = q->data;
free(q);
q = NULL;
return true;
}
bool is_empty(pnode phead)
{
if (!phead->pnext)
return true;
else
return false;

}
int length_list(pnode phead)
{
pnode p = phead;
int lon = 0;
while (p)
{
++lon;
p = p->pnext;
}
return lon;
}
void sort_list(pnode phead)
{
int i, j, t;
int len = length_list(phead);
pnode p, q;
for (p = phead->pnext; i < len - 1; p = p->pnext,i++)
for (q = p->pnext; j < len;q=q->pnext,j++)
if (p->data > q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
}
int main()
{
int val;
pnode phead = NULL;//等价于struct Node *phead = NULL;
phead = creat_list();//创建一个非循环单链表,并将该链表头节点地址赋给phead
traverse_list(phead);
int length = length_list(phead);
insert_list(phead, -4, 44);
delete_list(phead, 5, &val);
sort_list(phead);
system("pause");
return 0;
}

posted @ 2016-07-18 20:02  JungleHuter  阅读(168)  评论(0编辑  收藏  举报