Talk is good! But I will show you the code ?
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class LinkedList {
template <typename U>
friend LinkedList<U>* ring(vector<U>& vec);
private:
T data;
LinkedList* next;
public:
LinkedList() = default;
LinkedList(T& data)
: data(data)
, next(nullptr)
{
}
void traverse()
{
auto end = this;
auto walk = this;
do {
// do something here, like:
cout << walk->data << endl;
walk = walk->next;
} while (walk != end);
}
};
template <typename T>
LinkedList<T>* ring(vector<T>& vec)
{
LinkedList<T> fake, *tail = &fake;
for (auto& i : vec) {
auto node = new LinkedList<T>(i);
tail->next = node;
tail = node;
}
tail->next = fake.next; // Make a ring!
return fake.next;
}
int main(void)
{
vector<int> v = vector<int>({ 1, 2, 3, 4 });
auto node = ring(v);
node->traverse();
// Do some clean here...
return 0;
}
这样可以从任意一个节点出发遍历整个链表