#include<iostream>
//单链表
using namespace std;
template <typename Elemtype>
struct Node {
Elemtype data;
Node* next;
Node() {
//默认构造函数
next = NULL;
}
Node(Elemtype c) {
// 自定义构造函数
data= c;
next = NULL;
}
};
template <typename Elemtype>
struct Linklist {
typedef Node<Elemtype>Node;
Node head;
int length= 0 ;
void add(Elemtype e) {
// 添加结点
Node* q = new Node(e);
//q->next = p;
q->next = head.next;
head.next = q;
length++;
}
void tailadd(Elemtype e) {
//尾插法
Node* p = new Node(e); // 创建好新的结点信息
Node* tail = head.next;
while (tail->next) {
tail = tail->next; //指针移动到链表最后
}
p->next = tail->next;
tail->next = p;// 结点加入到末尾
length++;
}
void print() {
Node* p = head.next; //首元节点开始输出
cout << "head→";
while (p) {
cout << p->data << "→";
p = p->next;
}
cout << "^" << endl;
}
};
int main() {
Linklist<int>L;
for (int i = 2; i < 5; i++) {
L.add(i);
}
cout << "(2,3,4) 头插法:" << endl;
L.print();
for (int i = 6; i < 9; i++) {
L.tailadd(i);
}
cout << "(6,7,8) 尾插法:" << endl;
L.print();
return 0;
}
输出结果是:
(2,3,4) 头插法:
head→4→3→2→^
(6,7,8) 尾插法:
head→4→3→2→6→7→8→^
记得关注哦!