Golang concise iterative solution


  • 0

    Hold current node, previous node, and next node in each iteration.
    In each loop, we set current's Next to the previous node to reverse the direction. We store the original current.Next to next before reversing so that we won't lost the next node after the operation.

    Also, for the first node (head), we should not forget to set it's Next to nil because it would be the tail or the result.
    If we forget this, the list will have infinite cycle.

    func reverseList(head *ListNode) *ListNode {
    	if head == nil || head.Next == nil {
    		return head
    	}
    
    	prev, cur := head, head.Next
    	head.Next = nil // head should be tail after reversing
    	var next *ListNode
    	for {
    		next = cur.Next
    		cur.Next = prev
    
    		if next == nil {
    			return cur
    		}
    		prev = cur
    		cur = next
    	}
    	return nil // never reaches here
    }
    

Log in to reply
 

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