[LeetCode 206] Reverse Linked List (Easy)

Reverse a singly linked list.

Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
  • Follow up:
    A linked list can be reversed either iteratively or recursively. Could you implement both?

链表的基本功

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {        
        if (head == null || head.next == null)
        {
            return head;
        }
        
        ListNode prev = null;
        while (head != null)
        {
            ListNode next = head.next;
            head.next = prev;
            
            prev = head;
            head = next;
        }
        
        return prev;
    }
}

你可能感兴趣的:([LeetCode 206] Reverse Linked List (Easy))