How to compare two linked lists are equal in Python All In One

发布时间 2023-08-13 14:17:52作者: xgqfrms

How to compare two linked lists are equal in Python All In One

在 Python 中如何比较两个链表是否相等

# Definition for singly-linked list.

from typing import Optional

class ListNode:
  def __init__(self, val=0, next=None):
    self.val = val
    self.next = next

class Solution:
  def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
    # DFS / BFS
    def getLength(node):
      temp = node
      length = 1;
      while temp.next != None:
        length += 1
        temp = temp.next
      return length
    def dfs(node, length):
      temp = node
      # 向下取整除法
      l = length // 2
      while l > 0:
        l -= 1
        temp = temp.next
      return temp
    return dfs(head, getLength(head))

def SingleLinkedListGenerator(num: int) -> Optional[ListNode]:
  head = ListNode()
  temp = head
  for i in range(num):
    temp.next = ListNode(i + 1)
    temp = temp.next
  return head.next

i = SingleLinkedListGenerator(7)
r = [4,5,6,7]

print("input ", i)

# how to compare two linked lists are equal in Python ??? JSON.stringify(list)


"""
$ py3 ./876_middle-of-the-linked-list.py

"""

https://leetcode.com/problems/middle-of-the-linked-list/

# # test cases
# t1 = 14
# t2 = 8
# t3 = 123
# tests = [t1, t2, t3]

# r1 = 6
# r2= 4
# r3 = 12
# results = [r1, r2, r3]

# def test():
#   solution = Solution()
#   for index, test in enumerate(tests):
#     value = solution.numberOfSteps(test)
#     result = results[index]
#     if(str(value) == str(result)):
#       print("✅ passed", index)
#     else:
#       print("❌ failed", value, result)

# test()


solutions

def equal(self, other):
    while self and other and self.value == other.value:
        self = self.next
        other = other.next
    if not self and not other:
        return True
    return False

def check_equality(list_1, list_2):
   curr_1 = list_1.head
   curr_2 = list_2.head
   while (curr_1 and curr_2):
      if curr_1.data != curr_2.data:
         return False
      curr_1 = curr_1.next
      curr_2 = curr_2.next
   if curr_1 is None and curr_2 is None:
      return True
   else:
      return False

json

import json

list1 = [1,2,3]
list2 = [1,2,3]

result = json.dumps(list1) == json.dumps(list2)
print("result =", result)

"""

$ py3 ./json.stringify_json.dumps.py
result = True

"""

https://www.cnblogs.com/xgqfrms/p/17626511.html

demos

image

# Definition for singly-linked list.

from typing import Optional

class ListNode:
  def __init__(self, val=0, next=None):
    self.val = val
    self.next = next

class Solution:
  def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
    # DFS / BFS
    def getLength(node):
      temp = node
      length = 1;
      while temp.next != None:
        length += 1
        temp = temp.next
      return length
    def dfs(node, length):
      temp = node
      # 向下取整除法
      l = length // 2
      while l > 0:
        l -= 1
        temp = temp.next
      return temp
    return dfs(head, getLength(head))

# def SingleLinkedListGenerator(num: int) -> Optional[ListNode]:
#   head = ListNode()
#   temp = head
#   for i in range(num):
#     temp.next = ListNode(i + 1)
#     temp = temp.next
#   return head.next

def SingleLinkedListGenerator(num: int, start: int = 1) -> Optional[ListNode]:
  head = ListNode()
  temp = head
  for i in range(num):
    if(start == 1):
      temp.next = ListNode(i + start)
      # print("temp.next.val =", temp.next.val)
      temp = temp.next
    else:
      if(i < start):
        temp.next = ListNode(i + start)
        # print("temp.next.val =", temp.next.val)
        temp = temp.next
  return head.next


def compareListEqual(one, two):
  while one and two and one.val == two.val:
    one = one.next
    two = two.next
  # 同时为 None ✅
  if not one and not two:
    return True
  return False

input = SingleLinkedListGenerator(7)
# print("\n")
result = SingleLinkedListGenerator(7, 4)
# i = [1,2,3,4,5,6,7]
# r = [4,5,6,7]

solution = Solution()
case = solution.middleNode(input)

test = compareListEqual(case, result)
if test:
  print("✅ test =", test)
else:
  print("❌ test =", test)


(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/54388326/how-do-i-compare-two-linked-lists-in-python-3-7

https://www.tutorialspoint.com/python-program-to-check-whether-2-linked-lists-are-same

https://www.geeksforgeeks.org/python-program-to-check-if-two-linked-lists-are-identical/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!