本文链接:https://blog.csdn.net/caoshangpa/article/details/80362804
两两反转单链表就是把每两个数反转一次。如:
A -> B -> C ->D -> E -> F两两反转后变为 B -> A -> D ->C -> F -> E。
#include <iostream> using namespace std; struct Node{ int data; Node* next; }; void Display(Node *head)// 打印链表 { if (head == NULL) { cout << "the list is empty" << endl; return; } else { Node *p = head; while (p) { cout << p->data << " "; p = p->next; } } cout << endl; } Node* ReverseList(Node* head)// 两两反转链表 { if (head == NULL) return NULL; Node* cur = head; //记录下下个结点,下次的置换在该结点和该结点的下一个结点间进行 Node * nexnex = cur->next->next; //置换当前结点和下一个结点,例如,这一步后B指向A了,但是A依然指向B,目标是要A指向D。 Node * swaphead = cur->next; swaphead->next = cur; //递归,返回D Node * swapnexnex = ReverseList(nexnex); //使A指向D cur->next = swapnexnex; //最后返回B return swaphead; } Node* Init(int num) // 创建链表 { if (num <= 0) return NULL; Node* cur = NULL; Node* head = NULL; Node* node = (Node*)malloc(sizeof(Node)); node->data = 1; head = cur = node; for (int i = 1; i < num; i++) { Node* node = (Node*)malloc(sizeof(Node)); node->data = i + 1; cur->next = node; cur = node; } cur->next = NULL; return head; } int main( ) { Node* list = NULL; list = Init(10); Display(list); Node* newlist = ReverseList(list); Display(newlist); system("pause"); return 0; }
整个两两反转过程如下所示: