王道oj/problem17
网址:http:oj.lgwenda.com/problem17
思路:指针其实就是存储地址的一个空间,LinkList=LNode*
代码:
#define _CRT_SECURE_NO_WARNINGS
#include
#include
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;//指向下一个结点
} LNode,*LinkList;
//头插法新建链表
LinkList CreatList1(LinkList& L)//list_head_insert
{
LinkList s; int x;
L = (LinkList)malloc(sizeof(LNode));//带头结点的链表,指针就是存地址的一个空间
L->next = NULL;
scanf("%d", &x);
while (x!= 9999) {
s = (LinkList)malloc(sizeof(LNode));//申请一个新空间s,强制类型转换
s->data = x;//把读到的值,给新空间中的data
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
//尾插法
LinkList CreatList2(LinkList& L)//list_tail_insert
{
int x;
L = (LinkList)malloc(sizeof(LNode));
LNode* s, * r = L;//LinkList s,r = L;也可以
//s代表新结点,r代表表尾结点
scanf("%d", &x);
while (x!= 9999)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
void PrintList(LinkList L)//打印链表
{
L = L->next;
while (L != NULL)
{
printf("%d", L->data);
L = L->next;
if(L!=NULL)
printf(" ");
}
printf("\n");
}
int main()
{
LinkList L;//链表头,是结构体指针类型
CreatList1(L);//输入数据可以为3 4 5 6 9999
PrintList(L);
CreatList2(L);
PrintList(L);
return 0;
}