思路一:原始链表从表尾插入新元素,反转链表从表头插入新元素,见下面代码的函数reverse;
思路二:原地反转,当前节点的next指向下个节点的next,下个节点放在当前表头,见下面代码的函数reverse2。
show you my code:
#include <iostream>
using namespace std;
struct Node
{
int key;
Node* next;
};
Node* create(Node* head, int* data, size_t length);
Node* insert(Node* head, int value);
void print(Node* head);
Node* reverse(Node* head);
Node* insertFromHead(Node* head, int value);
Node* reverse2(Node* head);
int main(int argc, char *agrv[])
{
const size_t length = 10;
int data[length];
for(size_t i = 0 ; i < length ; i ++)
data[i] = i;
Node* head = NULL;
head = create(head, data, length);
print(head);
head = reverse2(head);
print(head);
return 0;
}
Node* create(Node* head, int* data, size_t length)
{
for(int i = 0; i < length; i ++)
{
head = insert(head, data[i]);
}
return head;
}
Node* insert(Node* head, int value)
{
if(!head)
{
head = new Node;
head->key = value;
head->next = NULL;
}
else
{
Node* now = NULL;
for(now = head; now->next != NULL; now = now->next)
{
}
Node* newNode = new Node;
newNode->key = value;
newNode->next = NULL;
now->next = newNode;
}
return head;
}
void print(Node* head)
{
for(Node* now = head; now != NULL; now = now->next)
{
cout<<now->key<<"@"<<(int)now<<" and next @"<<(int)now->next<<endl;
}
cout<<endl;
}
Node* reverse(Node* head)
{
Node* newHead = NULL;
for(Node* now = head; now != NULL; now = now->next)
{
newHead = insertFromHead(newHead, now->key);
}
return newHead;
}
Node* insertFromHead(Node* head, int value)
{
if(!head)
{
head = new Node;
head->key = value;
head->next = NULL;
}
else
{
Node* newNode = new Node;
newNode->key = value;
newNode->next = head;
head = newNode;
}
return head;
}
Node* reverse2(Node* head)
{
Node* tmp = NULL;
for(Node* now = head ; now->next != NULL ;)
{
tmp = now->next;
now->next = now->next->next;
tmp->next = head;
head = tmp;
}
return head;
}