翻转单链表是比较简单的事情,就像双向链表插入节点一样,关键在于指针的处理,除此之外没有什么值得关注的!
#include <iostream>
using namespace std;
struct list {
int value;
struct list *next;
};
struct list *insert(struct list *head, int v)
{
if (head) {
head->next = insert(head->next, v);
} else {
head = new struct list;
head->value = v;
head->next = 0;
}
return head;
}
struct list *reverse(struct list *head)
{
struct list *prev = 0, *next = 0;
while (head) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
void print(struct list *head)
{
cout << "list: ";
while (head) {
cout << head->value;
if (head->next) {
cout << "->";
}
head = head->next;
}
cout << endl;
}
int main()
{
struct list *head1 = 0;
head1 = insert(head1, 0);
head1 = insert(head1, 1);
head1 = insert(head1, 2);
head1 = insert(head1, 3);
head1 = insert(head1, 4);
head1 = insert(head1, 5);
head1 = insert(head1, 6);
head1 = insert(head1, 7);
head1 = insert(head1, 8);
head1 = insert(head1, 9);
print(head1);
head1 = reverse(head1);
print(head1);
return 0;
}