单链表反转
单链表反转:这个是反转是要破坏原有数据结构的。
算法1:红色线为将要修改节点的指向,这里只要关注几个节点:Head->next,Cur,Cur->next,Cur->next->next,遍历整个链表调整即可。
#include <iostream>
using namespace std; typedef struct _Node { struct _Node* next; int num; } Node; Node* reverse_list(Node* head) { Node* cur = NULL; Node* tmp = NULL; Node* last = NULL; if (NULL != head && NULL != head->next) { cur = head->next; while (cur != NULL && cur->next != NULL) { tmp = cur->next; last = tmp->next; cur->next = tmp->next; tmp->next = head->next; head->next = tmp; } } return head; } int main() { Node* head = new Node; Node* node1 = new Node; node1->num = 1; head->next = node1; Node* node2 = new Node; node2->num = 2; node1->next = node2; Node* node3 = new Node; node3->num = 3; node2->next = node3; Node* node4 = new Node; node4->num = 4; node3->next = node4; Node* node5 = new Node; node5->num = 5; node4->next = node5; node5->next = NULL; head = reverse_list(head); Node* tmp = head->next; while (tmp != NULL) { cout<<tmp->num<<endl; tmp = tmp->next; } return 0; }
算法2:用递归
Node* reverse_list(Node* head) { if (head->next == NULL) { return head; } Node* tmp = reverse_list(head->next); head->next->next = head; head->next = NULL; return tmp; }
不积跬步无以至千里,不积小流无以成江河。