Problem 206

Reverse Linked List

Posted by Ruizhi Ma on August 13, 2019

问题描述

https://leetcode.com/problems/reverse-linked-list/

代码

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

复杂度分析

  1. 时间复杂度:O(1)
  2. 空间复杂度:O(1)