- 两数相加
-
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
-
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: tmp = l1.val + l2.val res = ListNode(tmp%10) res_f = res flag = int(tmp/10) l1 = l1.next l2 = l2.next while l1 is not None or l2 is not None: if l1 is not None and l2 is not None: tmp = l1.val + l2.val + flag l1 = l1.next l2 = l2.next elif l1 is None and l2 is not None: tmp = l2.val + flag l2 = l2.next elif l1 is not None and l2 is None: tmp = l1.val + flag l1 = l1.next tmp_node = ListNode(tmp%10) flag = int(tmp/10) res.next = tmp_node res = res.next if flag == 1: res.next = ListNode(1) return res_f else: return res_f
通过
-
-
奇偶链表
-
给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。
-
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head or head.next is None: return head tmp1 = head tmp2 = head.next even = tmp2 while 1: if tmp2.next is not None: tmp1.next = tmp2.next tmp1 = tmp1.next else: tmp1.next = even break if tmp1.next is not None: tmp2.next = tmp1.next tmp2 = tmp2.next else: tmp2.next = None tmp1.next = even break return head
通过。不是最优方法,还有改进空间。
-
-
相交链表
-
编写一个程序,找到两个单链表相交的起始节点。
-
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: # hash dic_A = {} while headA is not None: dic_A[headA] = headA.val headA = headA.next while headB is not None: if headB in dic_A: return headB else: headB = headB.next return None # A = headA B = headB while A is not None and B is not None: if A == B: return A A = A.next B = B.next A = headB if A is None and B is not None else A B = headA if A is not None and B is None else B return None
通过。第一种是用hash的方法,对其中一个链表建立hash表,然后遍历另外一个。第二种方法是先找到两个链表,从后往前数,长度相同的部分。之后再一下一下往后移动指针,寻找相同的部分。
-
leetcode - 刷题记录-探索中级算法-链表
猜你喜欢
转载自blog.csdn.net/qq_32110859/article/details/105089630
今日推荐
周排行