题目
解答
struct ListNode {
int value;
ListNode* next;
ListNode(int val)
: value(val)
, next(NULL) {
}
};
void PrintList(ListNode* head) {
while (head != NULL) {
std::cout << head->value;
head = head->next;
if (head != NULL) {
std::cout << ", ";
}
}
std::cout << std::endl;
}
ListNode* ReverseList(ListNode* head) {
ListNode* new_head = NULL;
while (head != NULL) {
ListNode* backup_node = head->next;
head->next = new_head;
new_head = head;
head = backup_node;
}
return new_head;
}
ListNode* ReverseList2(ListNode* head) {
ListNode temp_head_node(-1);
while (head != NULL) {
ListNode* backup_node = head->next;
head->next = temp_head_node.next;
temp_head_node.next = head;
head = backup_node;
}
return temp_head_node.next;
}
int main() {
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
ListNode* head = &a;
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
PrintList(head);
ListNode* new_list_head = ReverseList(head);
PrintList(new_list_head);
ListNode* new_list_head2 = ReverseList2(new_list_head);
PrintList(new_list_head2);
return 0;
}