LeetCode上,Python单链表的定义
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
206. 反转链表
206. 反转链表(简单)
方法一: 迭代,双指针
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
prev = None
curr = head
while curr:
nex = curr.next
curr.next = prev
prev = curr
curr = nex
return prev
方法二: 递归
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
## 明确函数的意义
newhead = self.reverseList(head.next)
## 此时head.next成为以newhead为头结点的链表的尾结点
head.next.next = head
head.next = None
return newhead
19. 删除链表的倒数第N个节点
19. 删除链表的倒数第N个节点(中等)
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:
return head
# 虚拟头结点,删除头结点的情况不用额外分开讨论
dummyhead = ListNode(0)
dummyhead.next = head
slow = dummyhead
fast = dummyhead
while n:
fast = fast.next
n -= 1
# 此时slow指向需要删除的结点的头一个结点
while fast.next:
slow = slow.next
fast = fast.next
nex = slow.next.next
slow.next = nex
return dummyhead.next
83. 删除排序链表中的重复元素
83. 删除排序链表中的重复元素(简单)
题目给定的是排序链表,因此重复元素一定相邻,如果是未排序的,考虑使用集合辅助。
方法一: 双指针
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
prev = head
curr = head.next
while curr!=None:
if curr.val == prev.val:
prev.next = curr.next
else:
prev = curr
curr = curr.next
return head
方法二: 借助set
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
seen = set()
curr = head
prev = None
while curr:
nex = curr.next
if curr.val in seen:
prev.next = nex
else:
seen.add(curr.val)
prev = curr
curr = nex
return head
141. 环形链表
141. 环形链表(简单)
快慢指针 : 如果有环,快慢指针一定会相遇。
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head:
return False
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast==slow:
return True
return False
148. 排序链表
148. 排序链表(中等)
- 题目要求O(nlogn)的时间复杂度,考虑归并排序
具体来说,递归地分为两段,双指针
merge,参考21. 合并两个有序链表
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
mid = self.split(head)
left = self.sortList(head)
right = self.sortList(mid)
return self.merge(left,right)
def merge(self,left,right):
dummyhead = ListNode(-1)
curr = dummyhead
while left and right:
if left.val<right.val:
curr.next = left
left = left.next
else:
curr.next = right
right = right.next
curr = curr.next
if left:
curr.next = left
if right:
curr.next = right
return dummyhead.next
def split(self,head):
fast,slow = head,head
prev = None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = None
return slow
- 要求常数级的空间复杂度,如果考虑递归栈,则不能用递归
非递归实现参考 https://leetcode-cn.com/problems/sort-list/solution/sort-list-gui-bing-pai-xu-lian-biao-by-jyd/
参考资料:
https://github.com/datawhalechina/team-learning-program/blob/master/LeetCodeClassification/4.%20%E5%8F%8C%E6%8C%87%E9%92%88%E6%8A%80%E6%9C%AF.md