算法-02-反转链表

 描述

输入一个链表,反转链表后,输出新链表的表头。

Java 

复制代码
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
       if(head == null)
           return null;
        else
           return reverserList(head);
    }
    
    public ListNode reverserList(ListNode head){
        if(head.next==null)
           return head;
        ListNode last = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return last;
    }
}
复制代码

Python

复制代码
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead is None:
            return None
        else:
            return self.reverseList(pHead)
        
    def reverseList(self, pHead):
        if pHead.next is None:
            return pHead
        else:
            last = self.reverseList(pHead.next)
            pHead.next.next = pHead
            pHead.next = None
            return last
复制代码

 

posted @   sixinshuier  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
历史上的今天:
2019-07-19 13. VUE 组件之间数据传递
点击右上角即可分享
微信分享提示