【问题标题】:Why do my program prints None in the end?为什么我的程序最后打印 None ?
【发布时间】:2021-01-27 01:48:29
【问题描述】:

我正在自学算法和数据结构,并想编写一个程序,以下列方式合并两个链表:给定两个整数 a 和 b,它将从 a-th中删除节点> 从第一个链表到 b-th 并在其位置插入第二个链表。

我从here中获取了一个链表的实现并写了一个函数

def merge(list1: LinkedList, a: int, b: int, list2: LinkedList) -> LinkedList:

    current = list1.head
    previous = None
    insertion = list2.head
    counter = 0

    while insertion.next_node:
        insertion = insertion.next_node

    while current:
        if counter == a:
            previous.next_node = list2.head
        elif counter == b:
            insertion.next_node = current.next_node
        previous = current
        counter += 1
        current = current.next_node

    return list1.printList()

这是生成程序的完整代码:

class Node(object):
 
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node
 
 
class LinkedList(object):
    def __init__(self, head=None):
        self.head = head
 
    def size(self):
     current = self.head
     count = 0
     while current:
        count += 1
        current = current.next_node
     return count
       
    def printList(self): 
        temp = self.head 
        while (temp): 
            print (temp.data, " -> ", end = '') 
            temp = temp.next_node
        print("")
 
    def insert_at_head(self, data):
      new_node = Node(data)
      new_node.next_node = self.head
      self.head = new_node
 
    def get_next_node (self,node):
      return node.next_node.data

list1 = LinkedList(Node(0))
s = list1.head
for i in range(1,6):
    s.next_node = Node(i)
    s = s.next_node
list1.printList()

list2 = LinkedList(Node(99))
w = list2.head
for j in range(98,96,-1):
    w.next_node = Node(j)
    w = w.next_node
list2.printList()

def merge(list1: LinkedList, a: int, b: int, list2: LinkedList) -> LinkedList:

    current = list1.head
    previous = None
    insertion = list2.head
    counter = 0

    while insertion.next_node:
        insertion = insertion.next_node

    while current:
        if counter == a:
            previous.next_node = list2.head
        elif counter == b:
            insertion.next_node = current.next_node
        previous = current
        counter += 1
        current = current.next_node

    return list1.printList()

print(merge(list1, 1, 3, list2))

它按预期工作,只是它在输出末尾打印了一个额外的 None 。为什么它打印无?我错过了什么?

【问题讨论】:

    标签: python python-3.x list linked-list


    【解决方案1】:

    您的最后一行打印了您的merge 调用的返回merge 的返回是list.printList()。但是,list.printList() 没有定义返回值,所以它默认为None。请注意,list.printList() 在调用时仍然打印;它只是没有定义 return

    听起来您只是想在不打印的情况下调用merge。所以最后一行可能是:

    merge(list1, 1, 3, list2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-27
      • 2016-04-15
      • 2014-12-14
      • 2021-12-30
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多