1、尾插法创建一个单链表(带头结点)(顺序输入一个数组)
Linklist Createndlist(int a[N])
{
Linklist L;
L = (Lnode*)malloc(sizeof(Lnode));
if (L == NULL)
{
cout << "error";
exit(0);
}
else L->next = NULL;
Linklist tail, p;
tail = L;
int j;
for (j = 0; j < N; j++)
{
p = (Lnode*)malloc(sizeof(Lnode));
if (p == NULL)
{
cout << "error";
exit(0);
}
else p->next = NULL;
p->data = a[j];
tail->next = p;
tail = p;
}
tail->next = NULL;
return L;
}
2、头插法创建一个单链表(带头结点)(逆序输入一个数组)
Linklist Greatheadlist(int a[N])
{
int j;
Linklist L;
L = (Lnode*)malloc(sizeof(Lnode));
if (L == NULL)
{
cout << "error";
exit(0);
}
else L->next = NULL;
for (j = 0; j < N; j++)
{
Linklist p;
p = (Lnode*)malloc(sizeof(Lnode));
if (p == NULL)
{
cout << "error";
exit(0);
}
else p->next = NULL;
p->data = a[j];
p->next = L->next;
L->next = p;
}
return L;
}
3、尾插法创建一个单链表(不带头结点)(顺序输入一个数组)
Linklist Initendlist(int a[N]) //尾插法
{
Linklist L;
L = (Lnode*)malloc(sizeof(Lnode));
Linklist p; //设置工作指针p
p = L;
L->data = a[0];
for (int i = 1; i < N; i++)
{
Linklist q; //申请新结点q
q= (Lnode*)malloc(sizeof(Lnode));
q->data = a[i];
q->next = NULL;
p->next = q;
p = q;
}
return L;
}
4、头插法创建一个单链表(不带头结点)(逆序输入一个数组)
Linklist Initheadlist(int a[N]) //头插法
{
Linklist L;
L = (Lnode*)malloc(sizeof(Lnode));
Linklist tail;//设置工作指针
L->data = a[N-1];
for (int i = 0; i < N-1 ;i++)
{
Linklist q;//申请新节点
q=(Lnode*)malloc(sizeof(Lnode));
q->data = a[i];
tail = q;
tail->next = L->next;
L->next = tail;
}
return L;
}