写在前面:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 调用
new_list = ListNode(0)
1290. Convert Binary Number in a Linked List to Integer <倒序>
我做链表的第一道题:
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
n = 0
total = 0
plist = []
while(head):
n += 1
if head.val == 1:
plist.append(n)
head = head.next
for x in plist:
total += pow(2,n-x)
print(n,total)
return total
中心思想是要把给的head倒过来计算。有两种比较直接的思路:首先就是一一存出来倒着算,当然还有一种类似的看有人读了一遍长度,再重新读了一遍链表直接算;第二种就是把需要加的index记下来单独拿出来算。我写的是第二种思路。
如果对链表和python的指针不熟,比如像我现在这样,这题的重点就是从非常浅的层次来告诉你head.val == 1
、head = head.next
,以及直接从链表下手能干什么不能干什么。
<Floyd龟兔系列>
876. Middle of the Linked List
明明可以简单做的一道题,翻了很久discussion有绝妙的感悟。还记得大二数据结构课老师讲的检测loop吗!这个快慢指针思想就是可以放进去。放一下快慢指针最经典的用法 :
141. Linked List Cycle
def hasCycle(self, head):
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
142. Linked List Cycle II
追加一道题,除了判断是否是环以外,还有确定起点的位置。需要用到Floyd算法的思想:
- 确定有环:slow和fast相遇
- 确定起点的位置:一个在起点一个在相遇点,一次一步,相遇点即为起点。
参考代码:
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
else:
return None