反转链表

反转链表

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

相关推荐

程序员牛肉:你这简历有啥值得拷打的?在牛客你这种简历一抓一大把,也就是个人信息不一样而已。 关键要去找亮点,亮点啊,整个简历都跟流水线生产出来的一样。
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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