反转链表

反转链表

http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

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

方法一:递归

/*
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 || head.next == null) {
             return head;
         }
         ListNode res = ReverseList(head.next);
         head.next.next = head;
         head.next = null;
         return res;
    }
}

方法二:迭代

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode res = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = res;
            res = head;
            head = temp;
        }
        return res;
    }
}
全部评论
这个递归很漂亮很简洁,赞一个
点赞 回复 分享
发布于 2021-09-23 16:49

相关推荐

爱吃烤肠的牛油最喜欢...:50K是ssp了估计,ssp的人家多厉害都不用说,每年比例大概在百分之5左右
点赞 评论 收藏
分享
10-09 19:08
已编辑
门头沟学院 Java
后端转测开第一人:换个模版 技术栈写的精炼紧凑一点 多投就行
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务