c++单链表的头插尾插法
Description
from 王道C语言训练营
输入3 4 5 6 7 9999一串整数,9999代表结束,通过头插法新建链表,并输出,通过尾插法新建链表并输出。
注意输出要采用如下代码(因为OJ判题对空格敏感,因此需要用下面的打印代码来做):
//打印链表中每个结点的值
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct LNode{
ElementType data;
struct LNode *next;
}LNode, *LinkList;
void PrintList(LinkList L){
L=L->next;
while(L){
printf("%d", L->data);
L=L->next;
if(L)
{
printf(" ");
}
}
printf("\n");
}
LinkList list_head_insert(LinkList &L){
LinkList s;
ElementType insert_value;
scanf("%d", &insert_value); // 先输入一个数值
while(insert_value!=9999){
s=(LinkList)malloc(sizeof(LNode));
s->data=insert_value;
s->next=L->next;
L->next=s;
scanf("%d", &insert_value); //在一次循环结束后再输入
}
return L;
}
LinkList list_tail_insert(LinkList &L){
LinkList s, r=L;
ElementType insert_value;
scanf("%d", &insert_value);
while(insert_value!=9999){
s=(LinkList)malloc(sizeof(LNode));
s->data=insert_value;
r->next=s; // 让尾部节点指向新节点 s->next=r->next; 错误写法?
r=s; // 让r指向新的表尾节点
scanf("%d", &insert_value);
}
s->next=NULL; // 可以不写 也可以写成r->next=NULL
return L;
}
int main()
{
LinkList L, L2;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
L=list_head_insert(L);
PrintList(L);
L2=(LinkList)malloc(sizeof(LNode));
L2->next=NULL;
L2=list_tail_insert(L2); // L2->next=NULL; 要不要写?
PrintList(L2);
return 0;
}