1 #include<iostream> 2 using namespace std; 3 4 typedef struct LNode{ 5 int data; 6 LNode* next; 7 }LNode; 8 //非递归方法, 9 LNode* reverse(LNode* head) 10 { 11 if(!head||!head->next) 12 return head; 13 LNode *pre,*cur,*next; 14 pre = head; 15 cur = head->next; 16 next = cur->next; 17 pre->next = NULL; 18 while(next!=NULL) 19 { 20 next = cur->next; 21 cur->next = pre; 22 pre = cur; 23 cur = next; 24 } 25 head = pre; 26 return head; 27 } 28 //递归反转链表 29 LNode* reverseRecursion(LNode* currnode) 30 { 31 if(!currnode->next||!currnode) 32 { 33 return currnode; 34 35 } 36 else{ 37 38 LNode* temp = reverseRecursion(currnode->next); 39 LNode* nextnode = currnode->next; 40 nextnode->next = currnode; 41 currnode->next = NULL; 42 return temp;//返回当前节点 43 } 44 45 } 46 //创建链表 47 LNode* createList(int n) 48 { 49 LNode* head, *temp,*pre; 50 head = NULL; 51 head = new LNode; 52 head->data = n; 53 pre = head; 54 while(n--) 55 { 56 temp = new LNode; 57 temp->data = n; 58 pre->next = temp; 59 pre = temp; 60 } 61 pre->next = NULL; 62 return head; 63 64 } 65 66 int main(){ 67 int n =6; 68 LNode * list1,*list2,*temp1,*temp2; 69 list1 = createList(n);//初始链表 70 temp1 = list1; 71 while(n--) 72 { 73 cout<<"init node data:"<<temp1->data<<endl; 74 temp1 = temp1->next; 75 } 76 cout<<"head node data:"<<list1->data<<endl; 77 //list2 = reverse(list1); 78 list2 = reverseRecursion(list1); 79 n = 6; 80 temp2 = list2; 81 while(n--) 82 { 83 cout<<"reverse node data:"<<temp2->data<<endl; 84 temp2 = temp2->next; 85 } 86 return 0; 87 }