反转链表的解法分享

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语句以返回新链表的头结点
    }
};
相关推荐
CN-Dust1 天前
【C++】while语句例题专题
数据结构·c++·算法
xieliyu.1 天前
Java手搓数据结构:从零模拟实现无头双向非循环链表
java·数据结构·链表
如何原谅奋力过但无声1 天前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
jieyucx1 天前
Go 数据结构入门:线性表、顺序表、链表
数据结构·链表·golang
阿维的博客日记1 天前
zset为什么要用到skiplist+Dict的数据结构
数据结构·skiplist
洛水水1 天前
【力扣100题】17.K 个一组翻转链表
算法·leetcode·链表
洛水水1 天前
【力扣100题】16.两两交换链表中的节点
算法·leetcode·链表
编程之升级打怪1 天前
KMP查询算法的匹配串的前缀后缀相同的最大长度
数据结构
没文化的阿浩1 天前
【数据结构】排序(2)——直接选择排序、堆排序
数据结构·算法·排序算法
SunnyByte1 天前
线性表——双向链表
c语言·链表