-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206.Reverse Linked List.swift
91 lines (79 loc) · 2.23 KB
/
206.Reverse Linked List.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import Foundation
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
//利用数组将指针存储起来,然后逆序访问数组,构造一个反向链表,时间复杂度o(2n),空间复杂度o(1)
func reverseList(_ head: ListNode?) -> ListNode? {
guard head = head else {
return nil
}
var revList:ListNode? = nil;
var listArray = [ListNode]();
var p = head;
while p != nil {
listArray.append(p!);
p = p?.next;
}
var q:ListNode? = nil;
for index in (0..<listArray.count).reversed()
{
q = listArray[index];
if (index == listArray.count-1)
{
revList = q;
}
if (index > 0)
{
q?.next = listArray[index-1];
}
else
{
q?.next = nil;
}
}
return revList;
}
//首先用一个临时变量保存下一个结点位置,当前点的next指向前一个结点,前一结点=当前结点,然后当前结点指向下一结点位置,如此循环下去即可。时间复杂度o(n),空间复杂度o(1)
func reverseList2(_ head: ListNode?) -> ListNode? {
var pre: ListNode? = nil, curr = head
while curr != nil
{
let listTemp = curr?.next;
curr?.next = pre;
pre = curr;
curr = listTemp;
}
return pre
}
//递归逆序
func reverseList3(_ head: ListNode?) -> ListNode? {
if (head == nil)
{
return nil;
}
let p = head;
let q = reverseList(head?.next);
p?.next = nil;
if q != nil {
var tailq = q;
while tailq!.next != nil {
tailq = tailq!.next;
}
tailq!.next = p;
}
else {
return p;
}
return q;
}
}
let sol = Solution();
let x1 = ListNode(1),x2 = ListNode(2),x3 = ListNode(3)
x1.next = x2;x2.next = x3
sol.reverseList(x1)