非递归(迭代):从前向后遍历
递归:从后向前回溯
#include <iostream>
#include <string>
using namespace std;
struct LinkNode {
int data;
LinkNode* next;
};
// 迭代
LinkNode* ReverseLink(LinkNode* head) {
LinkNode *temp;
LinkNode *reversenode = NULL;
if (head==NULL)
return NULL;
while (head){
temp = head->next;
head->next = reversenode;
reversenode = head;
head = temp;
}
return reversenode;
}
// 递归
LinkNode* ReverseLinkRecursion(LinkNode* head) {
LinkNode *reverseHead, *current, *temp;
if (head == NULL)
return NULL;
if (head->next == NULL)
return head;
else {
current = head;
temp = head->next;
reverseHead = ReverseLinkRecursion(head->next);
temp->next = current;
current->next = NULL;
}
return reverseHead;
}
void PrintLink(LinkNode* head) {
if (head == NULL)
return;
while (head->next != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << head->data << endl;
}
void CreateLink() {
LinkNode node = { 1,NULL};
LinkNode node1 = { 2,NULL };
LinkNode node2 = { 3,NULL };
LinkNode node3 = { 4,NULL };
LinkNode node4 = { 5,NULL };
LinkNode node5 = { 6,NULL };
LinkNode node6 = { 7,NULL };
node.next = &node1;
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
node5.next = &node6;
PrintLink(&node);
LinkNode* reversenode;
reversenode = ReverseLink(&node);
PrintLink(reversenode);
}
int main()
{
CreateLink();
system("pause");
return 0;
}