1、单链表反转
力扣206
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 头插入法
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = head
rev = None
q = None
while p:
q = p.next # 临时保存下一个节点位置
p.next = rev
rev = p
p = q
return rev
2、链表中环的检测
使用快慢指针去判断是否成环,快指针每次步长为2,慢指针每次步长为1,如果快指针能追上慢指针则说明有环,否则表示没有环
力扣141
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = head
slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast==slow:
return True
return False
3、两个有序的链表合并
力扣21
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
result = head # 临时保存头指针的位置
while l1 and l2:
if l1.val <= l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
# 将剩余的长链表对接上
if l1:
head.next = l1
else:
head.next = l2
return result.next
三、删除链表倒数第 n 个结点
力扣19
实例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5
思路:
使用两个节点即快慢指针,一个是first一个是slow。先让first走n步,然后再让first和second同时往前走,当first走到头时,second即是倒数第n+1个节点了。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head is None:
return None
result = ListNode(0)
result.next = head
first = result
slow = result
while n>=0:
first = first.next
n -= 1
while first:
first = first.next
slow = slow.next
slow.next = slow.next.next
return result.next
四、求链表的中间结点
力扣876
给定一个带有头结点 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
思路一:
先遍历一遍链表得到链表的长度,然后求出中间的位置,最后在遍历到中间位置返回;
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
count = 0
p = head
while p:
p = p.next
count += 1
count = count//2
while count>0:
head = head.next
count -= 1
return head
思路二:
使用快慢指针,快指针步长为2,慢指针步长为1,当快指针遍历完成时,慢指针正好是中间位置;
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow