- [83.删除排序链表中的重复元素] (https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/)
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例
python
输入: 1->1->2
输出: 1->2
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
sen = ListNode(0)
sen.next = head
pre,cur = sen,head
rep = []
while cur:
if cur.val in rep:
pre.next = cur.next
else:
rep.append(cur.val)
pre = cur
cur = cur.next
return sen.next
- 82.删除排序链表中的重复元素
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例
python
输入: 1->2->3->3->4->4->5
输出: 1->2->5
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
dummy = ListNode(-1)
dummy.next = head
slow = dummy
fast = dummy.next
while fast:
while fast.next and slow.next.val == fast.next.val:
fast = fast.next
if slow.next == fast:
slow = fast
else:
slow.next = fast.next
fast = fast.next
return dummy.next
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
python
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
python
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
elif not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
elif l1.val>= l2.val:
l2.next = self.mergeTwoLists(l2.next,l1)
return l2
- 141.环形链表
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
示例
python
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
python
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
fast = head.next
slow = head
while slow!=fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
+142.环形链表 II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以使用 O(1) 空间解决此题?
示例
python
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
fast,slow = head,head
while True:
… fast = fast.next
slow = slow.next