浏览了一下 Leetcode 上 Linked List 的题目,我把它分为 6 类:
- 调换顺序
- 删除
- 合并
- 环
- 变身
- 复制
做Leetcode还是要归类总结才好玩,最开始做两三个觉得很懵,做四五个就能发现规律,找到适合自己的思考方式,剩下的题就都迎刃而解。打通任督二脉后,做题也会上瘾,练练脑子还挺好玩的。
每个题的源码和详细思路可以看这里。
目前做完:
- 调换顺序:234,147,206,24,143,328,61
- 删除:19,83,203,82
- 合并:21,160
- 环:141,142
- 变身:109,2
今天周六,是玩的时间,不过晚上回来还是做了几个题,其他题目如果感兴趣的话可以去上面的链接里看。
[1] 调换顺序
328,Odd Even Linked List
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
odd = oddHead = head
even = evenHead = head.next
while even and even.next:
odd.next = odd.next.next
even.next = even.next.next
odd = odd.next
even = even.next
odd.next = evenHead
return oddHead
61,Rotate List
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
if head is None or head.next is None or k == 0:
return head
dummy = ListNode(0)
dummy.next = head
# 计算length,求余数,求step
p = dummy #p从dummy开始,步数就可以和length保持一致
length = 0
while p.next: #p最后是走到尾部,而不是None,这样可以连接指向原head
length += 1
p = p.next
# 计算长度的同时,顺便把尾部指向原head
p.next = head
# 找到新head
step = length - k % length
while step > 0: #p从尾部开始,相当于从dummy开始,步数和step保持一致
p = p.next
step -= 1
dummy.next = p.next
p.next = None
return dummy.next
[2] 删除
82,Remove Duplicates from Sorted List II
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(0)
dummy.next = head
last = dummy
cur = head
while cur and cur.next:
p = cur.next
if p.val != cur.val:
last.next = cur
last = cur
cur = p
else:
while p and p.val == cur.val:
p = p.next
cur = p
last.next = cur
return dummy.next
我是 不会停的蜗牛 Alice
85后全职主妇
喜欢人工智能,行动派
创造力,思考力,学习力提升修炼进行中
欢迎您的喜欢,关注和评论!
网友评论