24、两两交换链表中结点
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
cur = dummy.next
pre = dummy
while cur:
if cur.next:
temp = cur.next.next
cur.next.next = cur
pre.next = cur.next
cur.next = temp
pre = cur
cur = temp
else:
break
return dummy.next
只用一个cur节点也可以,不过我嫌next接的太多,就加了pre指针看起来清爽点,主要是虚拟头节点的使用,判断好什么时候循环就行
19、删除链表倒数第N个结点
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
slow, fast = 0, 0
cur = dummy.next
while cur:
if cur.next:
fast += 1
cur = cur.next
cur = dummy
for i in range(fast+1):
if slow == fast+1-n:
cur.next = cur.next.next
return dummy.next
cur = cur.next
slow += 1
用笨方法AC了,这题真正的解法应用快慢指针法一遍扫描过,巧妙且简洁
面试题02.07 链表相交
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
dummyA = ListNode()
dummyA.next = headA
cur = dummyA.next
hash_map = {}
count = 0
while cur:
hash_map[cur] = count
cur = cur.next
count += 1
dummyB = ListNode()
dummyB.next = headB
cur = dummyB.next
inter_node = None
while cur:
if cur in hash_map:
inter_node = cur
break
cur = cur.next
return inter_node
用的哈希表存放已遍历过的节点这个方法,还可以先利用尾结点是否一致判断相交与否,再用长度差异走快慢指针法找出相交结点
142、环形链表II
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
hash_map = {}
cur = dummy
index = 0
while cur.next:
if cur.next not in hash_map:
hash_map[cur.next] = index
else:
return cur.next
cur = cur.next
index += 1
用的哈希表解决,非常简单,不过用快慢指针法解更有技巧性,两个方法最好都掌握