/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ classSolution{ funcreverseList(_head: ListNode?) -> ListNode? { varA=ListNode(0,head) var cur = head var lastHead = head while cur?.next !=nil { A.next = cur?.next cur?.next = cur?.next?.next A.next?.next = lastHead lastHead =A.next } return lastHead } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ funcreverseList(_head: ListNode?) -> ListNode? { if head ==nil|| head?.next ==nil { return head } var cur = head, pre =ListNode(0).next , nextP = head while cur !=nil { nextP = cur?.next cur?.next = pre pre = cur cur = nextP } return pre } }