一、链表初始化
typedef struct LNode
{
int data;
struct LNode* next;
}LNode,*LinkList;
void InitList(LinkList &L)
{
L = (LNode *)malloc(sizeof(LNode));
if(!L)
{
perror("List Init error");
return;
}
L->next = NULL;
}
二、节点的插入
(1)头插法
// 头插法
void headInsert(LinkList &L)
{
int elem;
while(scanf("%d",&elem) != EOF)
{
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = elem;
p->next = L->next;
L->next = p;
}
}
(2)尾插法
// 尾插法
void TailInsert(LinkList &L)
{
int elem;
LNode *p = L;
// scanf("%d",&elem);
while(scanf("%d",&elem) != EOF)
{
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = elem;
p->next = s;
p = s;
}
p->next = NULL;
三、整体演示
/*
单链表的建立方法:
1、头插法
2、尾插法
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode,*LinkList;
void InitList(LinkList &L)
{
L = (LNode *)malloc(sizeof(LNode));
if(!L)
{
perror("List Init error");
return;
}
L->next = NULL;
}
// 尾插法
void TailInsert(LinkList &L)
{
int elem;
LNode *p = L;
// scanf("%d",&elem);
while(scanf("%d",&elem) != EOF)
{
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = elem;
p->next = s;
p = s;
}
p->next = NULL;
}
// 头插法
void headInsert(LinkList &L)
{
int elem;
while(scanf("%d",&elem) != EOF)
{
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = elem;
p->next = L->next;
L->next = p;
}
}
void PrintList(LinkList L)
{
LNode *p = L->next;
while(p != NULL)
{
printf("%d\n",p->data);
p = p->next;
}
}
int main()
{
LinkList L;
InitList(L);
// TailInsert(L);
// PrintList(L);
headInsert(L);
PrintList(L);
return 0;
}