图解数据结构的部分题目
主要是链表的基本操作,不懂就记住吧。。顺便贴一下怎么在pycharm中调试链表相关的块:
# 用第一个listnode就可以了,一个个的创建节点
class ListNode():
def __init__(self,x):
self.val=x
self.next=None
class SingleLinkList:
def __init__(self, node=None):
self.__head = node
def is_Empty(self):
return self.__head is None
def append(self, item): # 尾插法
node = ListNode(item)
if self.is_Empty():
self.__head = node
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
def find_head(self):
return self.__head
**********
mm = Solution()
head = ListNode(None)
cur = head
for i in [2,4,7,8]: # 逐个生成节点
cur.next = ListNode(i)
cur = cur.next
head = head.next
res = mm.trainingPlan(head,1) # 调用
while res: # 输出
print(res.val, end=' ')
res = res.next
1.翻转句子
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseBookList(self, head):
"""
:type head: Optional[ListNode]
:rtype: List[int]
"""
stack = []
while head:
stack.append(head.val)
head = head.next
return stack[::-1]
2.删除特定值节点
class Solution(object):
def deleteNode(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head.val == val: # 要删除的是头结点
return head.next
pre = head
cur = pre.next
while cur and cur.val != val: # 链表没有到最后并且当前节点值不是val继续循环
pre = cur
cur = cur.next
if cur: # 找到val,直接覆盖删除
pre.next = cur.next
return head
3.翻转链表,初始化比较不一样,翻转过程注意暂存。画图理解
class Solution(object):
def trainningPlan(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
pre = None
cur = head
while cur:
tmp = cur.next # 暂存后继节点
cur.next = pre # 修改
pre = cur # 暂存当前节点
cur = tmp # 访问下一节点
return pre # 注意返回pre(不太懂。。)
4.反向找特定节点,用双指针。一开始想用count计算位置,挺好实现的
class Solution(object):
def trainingPlan(self, head, cnt):
"""
:type head: Optional[ListNode]
:type cnt: int
:rtype: Optional[ListNode]
"""
former = latter = head
for _ in range(cnt): # 前指针先走cnt个位置
former = former.next
while former: # 前后指针一起走,保持距离,当前指针指向空时后指针指向目标
latter = latter.next
former = former.next
return latter # 在lc里要这样写,能返回正确值
5.两个链表排序,用到插入节点
class Solution(object):
def trainningPlan(self, l1, l2):
"""
:type l1: Optional[ListNode]
:type l2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
cur = l = ListNode(0) # 建立一个新的链表来存结果,头结点为0
while l1 and l2: # 尾插法插入较小的节点,每插一个节点都要移动两个链表
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if not l1 and l2: # l1完了l2还有数时
cur.next = l2 # 把l2剩下的加入
if not l2 and l1:
cur.next = l1
return l.next # 返回除头结点外的节点
6.交叉链表,两条可能有重叠的链表找交汇节点。要求时间复杂度O(n) 空间复杂度O(1)。
指针A遍历完headA之后遍历headB,a+(b-c);同理,指针B走过 b+(a-c)。易知a+(b-c)=b+(a-c),并且之后一起指向相同部分(或者空)
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
A = headA # A B两个指针
B = headB
while A != B : # 如果A和B指向的是同一个节点则停止循环
A = A.next if A else headB # A指针遍历完headA开始遍历headB,到交汇处停止
B = B.next if B else headA
return A
写在最后:感觉链表就是瞎子,训练指针用法吧(虽然python弱化了指针的概念)