刷题23 反转链表

48 阅读1分钟

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

 

示例 1:

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

示例 2:

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

示例 3:

输入: head = []
输出: []

 

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

 

进阶: 链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题

题解:

迭代:

   class Solution {
public ListNode reverseList(ListNode head) {
    ListNode pre=null,cur=head;
    while(cur!=null){
        ListNode p=cur.next;
        cur.next=pre;
        pre=cur;
        cur=p;
    }
    return pre;
}
}

递归:

class Solution {
//1-2-3-4-5
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
        return head;
    } 
   // 1 -> 2 -> 3 -> 4 -> 5
    // head = 4, newHead = 5
    // head.next.next = head; head.next = null; 5->4,4->null
    // => 1 -> 2 -> 3 -> 4 <- 5
    // head = 3, newHead = 5
    // head.next.next = head; head.next = null; 4->3 3->null
    //=> 1 -> 2 -> 3 <- 4 <- 5
    // ...
    // head = 1, newHead = 5 (1 -> 2 <- 3 <- 4 <- 5)
    // head.next.next = head; head.next = null;  2->1 1->null
    //=> 1 <- 2 <- 3 <- 4 <- 5
    // return newHead; => newHead = 5 => 5 -> 4 -> 3 -> 2 -> 1
    ListNode newHead = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}
}