点:基本功
题意:单向链表逆序
剑指offer面试题16
思路:硬功夫
一定注意链表只有1个节点的情况,这种面试题专门在这种地方来恶心。
代码:
#include <iostream>
template<class T> struct Node {
int val;
Node<T> *next;
Node(T _val):val(_val), next(nullptr) {}
};
template<class T> class Slist {
Node<T> *root;
public:
Slist():root(nullptr) {}
~Slist() {
Node<T> *cur = root;
while (cur) {
Node<T> *next = cur->next;
delete cur;
cur = next;
}
}
void Add (int val) {
if (!root) {
root = new Node<T>(val);
} else {
Node<T> *cur = root;
while (cur) {
if (cur->next) {
cur = cur->next;
} else {
break;
}
}
Node<T> *newnode = new Node<T>(val);
cur->next = newnode;
}
}
void show () {
if (root) {
Node<T> *cur = root;
while (cur) {
std::cout << cur->val << "\t";
cur = cur->next;
}
std::cout << std::endl;
}
}
void Reverse () {
Node<T> *cur = root, *prev = cur, *next = cur->next;
if (!next) {
return;
}
while (cur) {
if (cur == root) {
cur->next = nullptr;
}
prev = cur;
Node<T> *nn = next->next;
next->next = prev;
cur = next;
next = nn;
if (!nn) {
root = cur;
break;
}
}
}
};
int main () {
Slist<int> sl;
for (int i = 0; i < 2; i++) {
sl.Add(i);
}
sl.show();
sl.Reverse();
sl.show();
return 0;
}