反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 输入: 1->2->3->4->5->NULL
 输出: 5->4->3->2->1->NULL
 */
class Solution {
    // 迭代解法
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    
    2 -> 3 -> 4 -> 5 -> null 
    1 -> null
   
    3 -> 4 -> 5 -> null
    2 -> 1 -> null
    
    4 -> 5 -> null
    3 -> 2 -> 1 -> null
    
    5 -> null
    4 -> 3 -> 2 -> 1 -> null
    
    null
    5 -> 4 -> 3 -> 2 -> 1 -> null
    
   
    // 递归解法
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

LeetCode 原题传送门

Q.E.D.


知识的价值不在于占有,而在于使用