您的位置:首页 > 其它

创建单向链表

2017-06-30 17:12 127 查看
算法描述1:正向创建单向链表(尾插方式)

//创建链表节点
typedef struct node
{
int data;
struct node *next;
}ElemSN;
//创建单向链表
ElemSN* CreatLink(int a[], int n)
{
int i;
ElemSN *ptail = NULL, *p = NULL, *h = NULL;
for (i = 0; i < n; i++)
{
p = (ElemSN*)malloc(sizeof(ElemSN));
//初始化数据域,初始化指针域
p->data = a[i];
p->next = NULL;
if (!h)//判断是否有头结点没有,创建头结点
{
h = p;
ptail = h;
}
else
{
ptail->next = p;//挂链
ptail = ptail->next;//挪尾指针
}
}
return h;
}


算法描述2:反向创建单向链表(头插方式)

//创建节点方式与正向建链相同
ElemSN* CreatLink(int a[], int n)
{
ElemSN *p = NULL, *h = NULL;
for (int i = n; i > 0; i--)
{
p = (ElemSN*)malloc(sizeof(ElemSN));
//初始化指针域,数据域
p->next = NULL;
p->data = a[i - 1];
p->next = h;//头插
h = p;//挪头指针
}
return h;
}


算法描述3:递归的方式创建单向链表日后会补上的

这里写代码片
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 算法