• 链表基本结构
• Dummy节点
• 尾插法
• 快行指针

# 基本结构

``````class ListNode {
var val: Int
var next: ListNode?

init(_ val: Int) {
self.val = val
self.next = nil
}
}
``````

``````class List {
var head: ListNode?
var tail: ListNode?

// 尾插法
func appendToTail(_ val: Int) {
if tail == nil {
tail = ListNode(val)
head = tail
} else {
tail!.next = ListNode(val)
tail = tail!.next
}
}

// 头插法
func appendToHead(_ val: Int) {
if head == nil {
head = ListNode(val)
tail = head
} else {
let temp = ListNode(val)
temp.next = head
head = temp
}
}
}
``````

# Dummy节点和尾插法

``````func partition(_ head: ListNode?, _ x: Int) -> ListNode? {}
``````

``````func getLeftList(_ head: ListNode?, _ x: Int) -> ListNode? {
let dummy = ListNode(0)
var pre = dummy
var node = head

while node != nil {
if node!.val < x {
pre.next = node
pre = node!
}
node = node!.next
}

node.next = nil
return dummy.next
}
``````

``````func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
// 引入Dummy节点
let prevDummy = ListNode(0)
var prev = prevDummy
let postDummy = ListNode(0)
var post = postDummy

var node = head

// 用尾插法处理左边和右边
while node != nil {
if node!.val < x {
prev.next = node
prev = node!
} else {
post.next = node
post = node!
}
node = node!.next
}

// 左右拼接
post.next = nil
prev.next = postDummy.next

return prevDummy.next
}
``````

# 快行指针

``````func hasCycle(_ head: ListNode?) -> Bool {
var slow = head
var fast = head

while fast != nil && fast!.next != nil {
slow = slow!.next
fast = fast!.next!.next

if slow === fast {
return true
}
}

return false
}
``````

``````func removeNthFromEnd(head: ListNode?, _ n: Int) -> ListNode? {
guard let head = head else {
return nil
}

let dummy = ListNode(0)
dummy.next = head
var prev: ListNode? = dummy
var post: ListNode? = dummy

// 设置后一个节点初始位置
for _ in 0 ..< n {
if post == nil {
break
}
post = post!.next
}

// 同时移动前后节点
while post != nil && post!.next != nil {
prev = prev!.next
post = post!.next
}

// 删除节点
prev!.next = prev!.next!.next

return dummy.next
}
``````

# 总结

• 一定要注意头结点可能就是nil。所以给定链表，我们要看清楚head是不是optional，在判断是不是要处理这种边界条件。
• 注意每个节点的next可能是nil。如果不为nil，请用"!"修饰变量。在赋值的时候，也请注意"!"将optional节点传给非optional节点的情况。