Swift - LeetCode - rearrange linked list

subject

Rearranging linked list

Question:

Given a single chain table L: L0 → L1 → →Ln-1→Ln ,
After rearrangement, it becomes: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 →

Advance:

You can't just change the internal values of nodes, but you need to actually exchange nodes.

Example:

Example 1:
     
Given the list 1 - > 2 - > 3 - > 4, rearrange it to 1 - > 4 - > 2 - > 3

Example 2:

Given the list 1 - > 2 - > 3 - > 4 - > 5, rearrange it to 1 - > 5 - > 2 - > 4 - > 3

Solutions:

First, find the location of the midpoint of the two linked lists, and then start from this midpoint, reverse the node of the linked list behind the midpoint, then point to the head node of the original linked list with a head pointer, and then point to the tail node of the linked list with a tail pointer, and then traverse from both sides to the middle. In the process of calendar, insert the node pointed to by the tail node into the back of the node pointed to by the head pointer.

Code:
/**
public class SingNode {
    public var value : Int
    public var nextNode: SingNode?
    
    public init(value:Int) {
        self.value = value
    }
}

extension SingNode : CustomStringConvertible {
    public var description: String {
        var string = "\(value)"
        var node = self.nextNode
        
        while node != nil {
            string = string + " -- " + "\(node!.value)"
            node = node?.nextNode
        }
        return string
    }
}
 **/
      
 func reorderList(_ l1:SingNode?) -> SingNode? {
        if l1 == nil || l1 == nil  {
            return l1
        }
        
        var p = l1
        var p2 = l1
        
        while p2?.nextNode != nil {
            p = p?.nextNode
            p2 = p2?.nextNode?.nextNode
            if p2 == nil {
                break
            }
        }
        print(p!)

        var pre = p
        var temp:SingNode? = nil
        p = p?.nextNode
        pre?.nextNode = temp
        while(p != nil){
            temp = p?.nextNode;
            p?.nextNode = pre;
            pre = p;
            p = temp;
        }
        
        var end = pre
        var first = l1

        while first != end {
            if first?.nextNode == end {
                break
            }
            
            let temp = end?.nextNode
            end?.nextNode = first?.nextNode
            first?.nextNode = end
            first = end?.nextNode
            end = temp
        }
        return l1
    }

Posted by Danny620 on Tue, 03 Dec 2019 02:58:32 -0800