在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a linked list, swap every two adjacent nodes and return its head. Example: Given Note:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 示例: 给定 说明:
8ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func swapPairs(_ head: ListNode?) -> ListNode? { 14 var current = head 15 16 let result = head?.next ?? head 17 18 while let next = current?.next { 19 let nextNext = next.next 20 next.next = current 21 current?.next = nextNext?.next ?? nextNext 22 current = nextNext 23 } 24 25 return result 26 } 27 } 12ms 1 class Solution { 2 func swapPairs(_ head: ListNode?) -> ListNode? { 3 var current = head 4 var next = current?.next 5 while next != nil { 6 (current!.val, next!.val) = (next!.val, current!.val) 7 8 current = current?.next?.next 9 next = current?.next 10 } 11 return head 12 } 13 } 20ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func swapNodes(pre: ListNode?, first: ListNode) { 14 let temp = first.next?.next 15 if pre != nil { 16 pre?.next = first.next 17 18 } 19 if first.next?.next != nil { 20 first.next?.next = first 21 first.next = temp 22 } else { 23 first.next?.next = first 24 first.next = nil 25 } 26 } 27 28 func swapPairs(_ head: ListNode?) -> ListNode? { 29 var pre: ListNode? = nil 30 var result = head 31 if let root = head { 32 if root.next != nil { 33 result = root.next 34 } 35 var current: ListNode? = head 36 while(current?.next != nil) { 37 swapNodes(pre: pre, first: current!) 38 pre = current 39 current = current?.next 40 } 41 } 42 43 return result 44 } 45 } 24ms 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func swapPairs(_ head: ListNode?) -> ListNode? { 14 guard let head = head else { 15 return nil 16 } 17 18 var left: ListNode? = head 19 var right = head.next 20 let root = head.next 21 while left != nil { 22 let temp = right?.next 23 right?.next = left 24 left?.next = temp?.next ?? temp 25 26 left = temp 27 right = temp?.next 28 } 29 30 return root ?? head 31 } 32 }
|
请发表评论