- 单向链表反转
#include <iostream>
#include <string>
#include <sstream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ostringstream;
namespace {
struct ListNode {
ListNode(int number, const string message)
:number_(number), message_(message)
{}
int number_;
string message_;
ListNode* next_;
};
void printList(ListNode* head)
{
ostringstream oss;
for (ListNode* temp = head; temp; temp = temp->next_) {
oss << "index:" << temp->number_ << " message:" << temp->message_ << '
';
}
cout << oss.str() << endl;
}
// return list head
ListNode* createList(size_t count)
{
string message;
std::allocator<ListNode> alloc;
ListNode *head, *current, *temp;
for (size_t i = 0; i < count; ++i) {
temp = alloc.allocate(sizeof(*temp));
cin >> message;
alloc.construct(temp, i, message);
if (i == 0) {
head = current = temp;
} else {
current->next_ = temp;
current = temp;
}
}
return head;
}
// return the new head
ListNode* reverseList(ListNode* head)
{
ListNode *current, *next, *prev = nullptr;
for (current = head; current; current = next) {
next = current->next_;
current->next_ = prev;
prev = current;
if (next == nullptr)
break;
}
return current;
}
void listTest(size_t n)
{
ListNode* head = createList(n);
if (head)
printList(head);
ListNode* rhead = reverseList(head);
if (rhead)
printList(rhead);
}
} // namespace
int main(void)
{
listTest(10);
return 0;
}