一.头插法示意图和代码如下
//头插法
struct ListNode* creatdanlianbaio()
{
int x = 0;
struct ListNode* p, * o, * temp = NULL;
p = NULL;
o = NULL;
scanf("%d", &x);
if (x != 9999)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->val = x;
p->next = NULL;
o=p;
}
scanf("%d", &x);
while (x != 9999)
{
temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->next = o;
temp->val = x;
o = temp;
scanf("%d", &x);
}
return o;
}
二.尾插法示意图和代码如下
struct ListNode* creatdanlianbaio()
{
//尾插法
int x = 0;
struct ListNode* p, * o, * temp = NULL;
p = NULL;
o = NULL;
scanf("%d", &x);
if (x != 9999)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->val = x;
o = p;
}
scanf("%d", &x);
while (x != 9999)
{
temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = x;
o->next = temp;
o = temp;
scanf("%d", &x);
}
o->next = NULL;
return p;
}
注意:无论是头插法还是尾插法都得先创建一个结点,其中头插创建的第一个节点始终在第一个位置,尾插创建的第一个节点始终在最后一个位置。