#include<iostream>
using namespace std;
typedef struct Lnode{
int data;
struct Lnode* next;
}Lnode ,* linklist;
//初始化单链表
//1,p指向一个新生成的节点,设为头节点,指针域设为null
int InitList(linklist &L) {
L= new Lnode;//注意这里是相同类型的指针!!!
L->next = NULL;//NULL全部是大写
return true;
}
//单链表的插入,分为前插法和后插法
void CreatLinst_H(linklist& L,int n) {//前插法要逆序插入
L = new Lnode;
L->next = NULL;
for (int i = 0; i < n; i++) {
linklist p;
p = new Lnode;
cout << "please input a value:" << endl;
cin >> p->data;
p->next = L->next;
L->next = p;
}
}
void CreatList(linklist &L,int n) { //相比与头插法,多了一个尾指针
L = new Lnode;
L->next = NULL;
Lnode* r;
Lnode* p;
r = L;
for (int i = 0; i < n; i++) {
p = new Lnode;
cout << "please input a value:" << endl;
cin >> p->data;
p->next = NULL;
r->next = p;
r = p;//r后移
}
}
void Printnode(linklist L) {
Lnode* q = L->next;
while (q!=NULL) {
cout << q->data << " " ;
q = q->next;
}
}
void test01() {
linklist L1;
InitList(L1);
cout << "The end of the method!" << endl;
CreatList(L1, 5);
Printnode(L1);
}
void test02() {
linklist L2;
InitList(L2);
cout << "The first method!" ;
CreatLinst_H(L2, 5);
Printnode(L2);
}
int main() {
test01();
cout << "---------------" << endl;
test02();
}