反转链表的解法分享

1、双指针法
cpp 复制代码
 ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
       ListNode* ReverseList(ListNode* pHead){
            if(pHead == NULL)
                return NULL;
            ListNode* cur = pHead;
            ListNode* pre =NULL;
            while(cur != NULL)
            {
                ListNode* temp = cur->next;
                cur->next = pre;
                pre = cur;
                cur = temp;
            }
            return  pre;
       } 
    }
2、递归写法
cpp 复制代码
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        return reverse(head,nullptr);
    }
    ListNode* reverse(ListNode* cur, ListNode* pre) {
        if (cur == nullptr) return pre;

        ListNode* temp = cur->next;
        cur->next = pre;
        return reverse(temp, cur); // 添加return语句以返回新链表的头结点
    }
};
相关推荐
学习中的码虫1 小时前
数据结构中的高级排序算法
数据结构·算法·排序算法
闪电麦坤952 小时前
数据结构:树(Tree)
数据结构
Musennn3 小时前
102. 二叉树的层序遍历详解:队列操作与层级分组的核心逻辑
java·数据结构·算法·leetcode
学习中的码虫3 小时前
c 中的哈希表
数据结构·哈希算法·散列表
ll77881113 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
Akiiiira14 小时前
【数据结构】栈
数据结构
c6lala14 小时前
数据结构day1
数据结构
多多*14 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
逐光沧海15 小时前
数据结构基础--蓝桥杯备考
数据结构·c++·算法·蓝桥杯
kedvellek17 小时前
Linux 内核链表宏的详细解释
linux·运维·链表