无法一次又一次地在LinkedList中插入相同的元素

阿杰(Ajay Bhagchandani)

码:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def create_list():
    seq = input("Enter the sequence of integers: ").split()
    int_seq = [int(i) for i in seq]
    head = None
    tail = None
    for number in int_seq:
        if number == -1:
            break
        node = Node(number)
        if head is None:
            head = node
            tail = node
        else:
            tail.next = node
            tail = node

    return head, tail

def count_no_of_elements(head):
    if head is None:
        return 0
    curr = head
    counter = 0
    while curr:
        curr = curr.next
        counter += 1
    return counter

def insert_element(head, tail, elem, posn):
    no_of_elem = count_no_of_elements(head)
    if posn <= 0 or posn > no_of_elem + 1:
        return -1, -1

    if posn == 1:       # Insert at the beginning
        element = Node(elem)
        element.next = head
        head = element
        return head, tail

    else:           
        counter = 1
        curr = head
        while counter != (posn - 1):
            curr = curr.next
            counter += 1
        element = Node(elem)
        if curr.next is not None: # Insert in between
            element.next = curr.next 
            curr.next = element
        else:                      # Insert at the end
            curr.next = element
            tail = element
        return head, tail

def traverse_list(head):
    if head is None:
        return -1
    curr = head
    while curr:
        print(curr.data)
        curr = curr.next
    return head       

按照以下顺序创建列表后1 3 5 7 9 2 4 8 6 0 -1

我正在尝试0在开头连续插入3次。

驱动程序代码:

list_head, list_tail = create_list()
# 1 3 5 7 9 2 4 8 6 0 -1

ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
if ins_hd != -1:
    trav = count_no_of_elements(ins_hd)
    print(trav)
    print('\n\n')
else:
    print(ins_hd)

if ins_hd != 1:
    trav = traverse_list(ins_hd)
print(in_tl.data)

插入代码从第二次开始不起作用。

实际输出:

11



0
1
3
5
7
9
2
4
8
6
0
0

我在这里想念什么?

亭子

从函数中获取返回值时,必须停止使用head和tail的旧值。您需要继续使用从插入中获得的新值。目前您不这样做:

ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
ins_hd, in_tl = insert_element(list_head, list_tail, 0, 1)
# ...

将其更改为使用相同的变量:

list_head, list_tail = insert_element(list_head, list_tail, 0, 1)
list_head, list_tail = insert_element(list_head, list_tail, 0, 1)
# ...

在这些语句之后的代码中还使用了list_headlist_tail

使它更加面向对象

我还建议为您的链表创建一个类,以使其在状态中保持其头部和尾部的变化值。这肯定会使代码更整洁,当然当您开始在同一代码中使用多个链接列表时:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self, int_seq=[]):
        self.head = None
        self.tail = None
        for number in int_seq:
            node = Node(number)
            if self.head is None:
                self.head = node
            else:
                self.tail.next = node
            self.tail = node

    def size(self):
        if self.head is None:
            return 0
        curr = self.head
        count = 0
        while curr:
            curr = curr.next
            count += 1
        return count

    def insert(self, elem, posn=1):
        if posn == 1:    # Insert before head
            node = Node(elem)
            node.next = self.head
            self.head = node
            return
        curr = self.head
        while curr.next is not None and posn > 2:
            curr = curr.next
            posn -= 1
        if posn != 2:
            raise ValueError("Invalid position")
        node = Node(elem)
        node.next = curr.next
        curr.next = node
        if curr == self.tail: # Insert after tail
            self.tail = node
        else:                 # Insert in between
            curr.next = node

    def values(self):
        curr = self.head
        while curr is not None:
            yield curr.data
            curr = curr.next

seq = input("Enter the sequence of integers: ").split()
llist = LinkedList([int(i) for i in seq])
# 1 3 5 7 9 2 4 8 6 0

llist.insert(0, 1)
print("size: {}".format(llist.size()))
print("values: {}".format(list(llist.values())))
llist.insert(10, 12)
print("size: {}".format(llist.size()))
print("values: {}".format(list(llist.values())))
llist.insert(11, 5)
print("size: {}".format(llist.size()))
print("values: {}".format(list(llist.values())))

在上面的代码中,我保持了相同的概念posn,因此在位置1插入意味着插入将发生头节点之前许多人会发现将其实际定义为位置0更自然,但我保留了原样。

我看不出要处理输入值-1的意义,因为您可以读取和插入所有值,因此我删除了该逻辑。

当给定的插入位置超出范围时,我认为引发异常更为合适。

同样,计算元素数量来确定位置是否在范围之内也是一种矫kill过正,因为您需要以任何方式遍历列表。所以,你可以在确定的位置的有效性迭代。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

机械手一次又一次地打印相同的字符串

为什么CoreBluetooth一次又一次地发现相同的外围设备?

内核一次又一次地死亡

OnNavigationItemsSelected侦听器一次又一次地启动相同的活动

jQuery在突出显示的段落中,它一次又一次地添加相同的文本

如何一次又一次地重复(递归)查询?

Flutter:为什么setState((){})一次又一次地设置数据

一次又一次地向多维数组添加“简单”数组元素

随着鼠标一次又一次地输入相同的链接,执行次数增加

如何在html中重复代码而不一次又一次地写相同的代码

如何一次又一次地选择读/写?

一次又一次地馈送avconv

如何一次又一次地调用URL

init方法在servlet中一次又一次地调用

是否必须一次又一次地定义地图?

高效的jQuery / JS-避免一次又一次地复制粘贴相同的代码

避免一次又一次地从JSON获取数据

通知被一次又一次地触发

makefile为不同的对象一次又一次地选择相同的源文件

要重用jQuery函数,使函数一次又一次地使用

查看传呼机一次又一次地刷相同的图像

如何停止在 JavaScript 中一次又一次地调用相同的函数?

在 Fortran 95 中一次又一次地读取文件的内容

Stripe Payment API 一次又一次地发送令牌请求

一次又一次地从 FB-Messanger Webhook 获取相同的消息

Azure 容器实例一次又一次地失败

Square 一次又一次地改变速度

更新状态一次又一次地获取数据后

一次又一次地编辑python脚本文件