常规解法(递归)

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   ArrayList<Integer> list=new ArrayList();
    public ListNode reverseList(ListNode head) {
         
        rec(head);
        ListNode p=head;
        int len=list.size();
       for(int i=0;i<len;i++)
       {
           p.val=list.get(i);
           p=p.next;
       }
    
        return head;

    }

    void rec(ListNode head){
        ListNode p=head;
        if(p==null)return;
        else
            rec(p.next);
        list.add(p.val);

    }
}
复制代码

原地反转(时空复杂度都有很大提高)

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   
    public ListNode reverseList(ListNode head) {

        ListNode pre=null;
        ListNode cur=head;
        while(cur!=null)
        {
            ListNode temp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=temp;
        }
       return pre;
        


    }

    
}
复制代码

 

posted on   upupup-999  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!



点击右上角即可分享
微信分享提示