剑指offer12-反转链表

186 阅读1分钟

反转链表

题目描述

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

思路1

  • 如图:以3个节点为例。

程序(java)
     /**
     * code1
     * 时间复杂度:O(n)
     * 时间复杂度:O(1)
     */
public ListNode ReverseList(ListNode head) {
    ListNode pre = null;
    ListNode next = head;
    while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/

思路2

  • 递归
程序(java)
     /**
     * code2
     * 时间复杂度:O(n)
     * 时间复杂度:O(n)
     */
public ListNode ReverseList(ListNode head) {
     if (head == null || head.next == null) {
         return head;
     }

     ListNode p = reverseList3(head.next);//p,新链表表头
     head.next.next = head;
     head.next = null;
     return p;
}