门户网站 解决方案,贵阳网站推广有几家,浙江最近爆发的传染病,可画人物插画设计1.两两交换列表中的节点 给你一个链表#xff0c;两两交换其中相邻的节点#xff0c;并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题#xff08;即#xff0c;只能进行节点交换#xff09;。 输入#xff1a;head [1,2,3,4]
输出#xff1a;[2… 1.两两交换列表中的节点 给你一个链表两两交换其中相邻的节点并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题即只能进行节点交换。 输入head [1,2,3,4]
输出[2,1,4,3] class ListNode:def __init__(self, val0, nextNone):self.val valself.next next
class Solution:def swapPairs(self, head):dummy_nodeListNode(nexthead)curdummy_nodewhile cur.next!None and cur.next.next!None:tempcur.nexttemp1cur.next.next.nextcur.nextcur.next.nextcur.next.nexttemptemp.nexttemp1curcur.next.nextreturn dummy_node.next 2.删除链表的倒数第N个数 给你一个链表删除链表的倒数第 n 个结点并且返回链表的头结点。 输入head [1,2,3,4,5], n 2
输出[1,2,3,5] #Definition for singly-linked list.
class ListNode:def __init__(self, val0, nextNone):self.val valself.next next
class Solution:def removeNthFromEnd(headn):dummy_nodeListNode(nextnext)fastlowdummy_nodefor i in range(n1):fastfast.nextwhile fast:fastfast.nextlowlow.nextlow.nextlow.next.nextreturn dummy_node.next3.链表相交 给你两个单链表的头节点 headA 和 headB 请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点返回 null 。 图示两个链表在节点 c1 开始相交 输入intersectVal 8, listA [4,1,8,4,5], listB [5,0,1,8,4,5], skipA 2, skipB 3
输出Intersected at 8
解释相交节点的值为 8 注意如果两个链表相交则不能为 0。
从各自的表头开始算起链表 A 为 [4,1,8,4,5]链表 B 为 [5,0,1,8,4,5]。
在 A 中相交节点前有 2 个节点在 B 中相交节点前有 3 个节点。 # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val x
# self.next Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) - ListNode:lenA,lenB0,0curheadAwhile cur:curcur.nextlenA1curheadBwhile cur:cur cur.nextlenB1curA,curBheadA,headBif lenA lenB:curA,curBcurB,curAlenA,lenBlenB,lenAfor i in range(lenB-lenA):curBcurB.nextwhile curA:if curAcurB:return curAelse:curAcurA.nextcurBcurB.nextreturn None