1.反转链表
// 头插法反转链表
func reversalLinkList(header: LinkNode?) -> LinkNode? {
var tmpheader: LinkNode? = header
var new_head: LinkNode? = nil;
var temp: LinkNode? = nil
if tmpheader == nil || tmpheader?.next == nil {
return header
}
while tmpheader != nil {
temp = tmpheader
tmpheader = tmpheader?.next
temp?.next = new_head
new_head = temp
}
return new_head
}
2.链表中环的检查
// 链表中环的检查 快慢指针
func checkLinkLoop(head: LinkNode?) -> Bool {
if head == nil {
return false
}
var fast: LinkNode? = head?.next
var slow: LinkNode? = head
while fast != nil {
if fast === slow {
return true
}
fast = fast?.next?.next
slow = slow?.next
}
return false
3.两个有序的链表合并
func mergeSortedLinkList(headA: LinkNode?, headB: LinkNode?) -> LinkNode? {
guard let headA = headA else {
return headB
}
guard let headB = headB else {
return headA
}
var head: LinkNode?, tail: LinkNode?
var nodeA: LinkNode? = headA
var nodeB: LinkNode? = headB
if headA.value < headB.value {
head = headA
nodeA = nodeA?.next
} else {
head = headB
nodeB = nodeB?.next
}
tail = head
while nodeA != nil && nodeB != nil {
if nodeA?.value ?? 0 < nodeB?.value ?? 0 {
tail?.next = nodeA
nodeA = nodeA?.next
} else {
tail?.next = nodeB
nodeB = nodeB?.next
}
tail = tail?.next
}
if nodeA != nil {
tail = nodeA
}
if nodeB != nil {
tail = nodeB
}
return head
}
4.删除链表倒数第n个结点
// 删除第N个结点 需要知道N-1结点 然后通过 a.next = a.next.next
func deleteNode(at index: Int, head: LinkNode?) -> LinkNode? {
var headerA = head
if head == nil || head?.next == nil {
return nil
}
var slow: LinkNode? = headerA
var fast: LinkNode? = headerA
var num = 1
while fast != nil, num < index {
fast = fast!.next
num += 1
}
// 越界
if fast == nil {
return nil
}
var previousNode: LinkNode? = headerA
while fast != nil {
previousNode = slow
fast = fast?.next
slow = slow?.next
}
if previousNode === headerA {
headerA = headerA?.next
} else {
// 删除某一结点
var tmpHeader: LinkNode? = headerA
var tmpPreviousHeader: LinkNode? = headerA
while tmpHeader != nil {
if previousNode === tmpHeader {
break
}
tmpPreviousHeader = tmpHeader
tmpHeader = tmpHeader?.next
}
tmpPreviousHeader?.next = slow
}
return headerA
}
5. 求链表的中间结点
func findCenterNode(head: LinkNode?) -> LinkNode? {
guard let headerA = head else {
return nil
}
var slow: LinkNode? = headerA
var fast: LinkNode? = headerA
while fast?.next != nil, fast?.next?.next != nil {
fast = fast?.next?.next
slow = slow?.next
}
return slow
}
LinkNode 定义
class LinkNode {
var value = 0
var next: LinkNode?
init(val: Int, next: LinkNode?) {
self.value = val
self.next = next ?? nil
}
}
网友评论