反转链表:
方法一:迭代(双指针)
考虑遍历链表,并在访问各节点时修改 next 引用指向。多创建一个指针prev和指针curr进行交换指向,达到改变各节点的指向目的。
#include#include struct node { //用结构体变量和指向结构体变量的指针构成链表 int num; struct node* next; //*next表示指向node这个结构体的指针变量 }; class Solution { public: node* reverseList(node* head) { node* cur = head, * pre = NULL; while (cur != NULL) { node* tmp = cur->next; // 暂存后继节点 cur.next cur->next = pre; // 修改 next 引用指向 pre = cur; // pre 暂存 cur cur = tmp; // cur 访问下一节点 } node* temp = pre; while (temp!= NULL) { //遍历一下看结果 std::cout << temp->num << std::endl; temp = temp->next; } return pre; //返回的是反过来的链表的头地址 } }; int main() { node a,b, * head, * p; a.num = 1; b.num = 2; head = &a; a.next = &b; b.next = NULL; Solution text; text.reverseList(head); }
方法二:递归
考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。



