反转链表的解法分享

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 小时前
算法篇—返回倒数第k个节点
c语言·数据结构·算法·leetcode
无忧.芙桃1 小时前
数据结构之堆
c语言·数据结构·c++·算法·
小蒋学算法2 小时前
算法-删除元素后最大固定点数目-典型最长增长序列算法
数据结构·算法
白白白小纯3 小时前
算法篇—链表的中间节点
c语言·数据结构·算法·leetcode
pluviophile_s4 小时前
数据结构:第6讲:树与二叉树
数据结构·笔记
来一碗刘肉面5 小时前
字符串模式匹配(朴素模式匹配算法与KMP算法)
数据结构·算法
code bean19 小时前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
storyseek20 小时前
前缀和实现Kogge-Stone算法
数据结构·算法
元Y亨H21 小时前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法
元Y亨H21 小时前
数据结构与算法的通俗指南
数据结构·算法