反转链表的解法分享

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语句以返回新链表的头结点
    }
};
相关推荐
永远睡不够的入38 分钟前
直接插入排序、希尔排序、选择排序
数据结构·算法·排序算法
历程里程碑39 分钟前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
LYFlied2 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
永远睡不够的入3 小时前
快排(非递归)和归并的实现
数据结构·算法·深度优先
cheems95273 小时前
二叉树深搜算法练习(一)
数据结构·算法
sin_hielo3 小时前
leetcode 3074
数据结构·算法·leetcode
风筝在晴天搁浅4 小时前
hot100 234.回文链表
数据结构·链表
徐子童5 小时前
优选算法---哈希表
数据结构·算法·哈希表
B_lack0265 小时前
字节转换算法应用_读取本地时间
数据结构·算法·数组·西门子plc·博途·时间处理·scl
2401_841495646 小时前
【LeetCode刷题】跳跃游戏Ⅱ
数据结构·python·算法·leetcode·数组·贪心策略·跳跃游戏