LeetCoded第206题题解--反转链表

反转一个单链表。

示例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

方法一:递归

自始至终每个递归返回的都应该是最后一个节点,每次递归将head.next指向head
在这里插入图片描述
代码

	public static ListNode reverseList(ListNode head) {
    
    
        if (head==null||head.next==null){
    
    
            return head;
        }
        ListNode listNode = reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return listNode;
    }

方法二:迭代

使用三个指针,pre指向前一个节点,cur指向当前节点,next指向下一个节点,让cur指向pre,并向后循环操作
在这里插入图片描述

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

猜你喜欢

转载自blog.csdn.net/qq_38723677/article/details/109146564
今日推荐