An working Swift solution but need improvement


  • 0
    L
    public func oddEvenList(head: ListNode?) -> ListNode? {
            
            if head == nil || head?.next == nil {
                return head
            }
            var headCopy = head
            
            var index = 1
            let oddHead = ListNode(val: head!.val)
            var oddTail = oddHead
            oddHead.next = oddTail
            
            let evenHead = ListNode(val: head!.next!.val)
            var evenTail = evenHead
            evenHead.next = evenTail
            
            while headCopy != nil {
                if index % 2 != 0 {
                    
                    oddTail.next = ListNode(val: headCopy!.val)
                    oddTail = oddTail.next!
                } else {
                    evenTail.next = ListNode(val: headCopy!.val)
                    evenTail = evenTail.next!
                }
                
                index++
                headCopy = headCopy!.next
            }
            oddTail.next = evenHead.next
            return oddHead.next
            
        }

Log in to reply
 

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