反转一个单链表。

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

方法一:递归

自始至终每个递归返回的都应该是最后一个节点,每次递归将head.next指向head
LeetCoded第206题题解--反转链表
代码

	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,并向后循环操作
LeetCoded第206题题解--反转链表

    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;
    }

相关文章:

  • 2021-10-19
  • 2022-12-23
  • 2022-01-14
  • 2021-04-21
猜你喜欢
  • 2022-12-23
  • 2021-08-29
  • 2021-07-10
  • 2021-07-12
  • 2021-12-29
  • 2021-08-25
相关资源
相似解决方案