0
点赞
收藏
分享

微信扫一扫

反转链表的实现(三种方法)

五殳师兄 2022-05-06 阅读 77

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例1:

 

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例2:

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]
/**
 * 反转链表
 * 可以用迭代和递归方式来完成反转
 */
public class Num206 {
    public ListNode reverseList(ListNode head) {
       //先判断边界条件  头插法
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = null;
        while (head != null){
            //遍历原链表,取出值,新建节点,头插法插入新建链表中
            ListNode node = new ListNode(head.val);
            node.next = newHead;
            newHead = node;
            head = head.next;
        }
        return newHead;
        /**
         * 要求空间复杂度为一
         * 将相邻两个节点的指向互换
         */
         if (head == null || head.next == null){
             return head;
         }
         ListNode prev = null;
         ListNode cur = head;
         while (cur != null){
             //使用next暂存下一个要处理的节点
             ListNode next = cur.next;
             cur.next = prev;
             prev = cur;
             cur = next;
         }
         return prev;
        /**
         * 递归法解决
         */
        if (head == null || head.next == null){
            return head;
        }
        //此时第二个节点以及以后的节点反转交给递归执行,并且返回链表的头就是最后要返回的值
        ListNode secNode = head.next;
        ListNode newHead = reverseList(head.next);
        secNode.next = head;
        head.next = null;
        return newHead;

    }

}

 

举报

相关推荐

0 条评论