Two Different Java Solution, O(n), In-place


  • 0
    X
    //Reverse Linked List
    //Solution 1
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null)    return head;
            ListNode slow=null, mid=null, fast=head;
            while(fast != null){
                slow = mid;
                mid = fast;
                fast = fast.next;
                mid.next = slow;
            }
            return mid;
        }
    }
    
    //Solution 2
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null)    return head;
            ListNode start=new ListNode(0), then=head.next;
            start.next = head;
            while(then != null){
                head.next = then.next;
                then.next = start.next;
                start.next = then;
                then = head.next;
            }
            return start.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.