是否按字母顺序在列表中添加名称?

时间:2018-06-20 18:21:51

标签: python-3.x data-structures linked-list singly-linked-list

假设我有一个名字的链接列表。每个节点均按字母顺序放置。如何正确遍历并在正确的位置插入名称?我们假设它是不区分大小写的。

def add(self, name):
    if self._size == 0:
        self.add_first(name)
        self._size += 1
    elif self._size >= 1:
        cur = self._head
        while name.upper() > cur.upper() or cur.get_next is not None:

这就是我被困住的地方

一个节点的编码如下

class Node():
    def __init__(self, element, next_node=None):
        self._element = element
        self._next = next_node

    def set_next(self, next_node):
        self._next = next_node

    def set_element(self, element):
        self._element = element

    def get_next(self):
        return self._next

    def get_element(self):
        return self._element

1 个答案:

答案 0 :(得分:0)

下面是一个通用的迭代实现。您必须将其调整为适合链接列表类。

class Node:
    def __init__(self, val, _next):
        self.val = val
        self.next = _next 
    def add(self, name):
        up = name.upper()
        if up < self.val.upper():
            return Node(name, self)  
            # We could also change self.val to update the head 
            # without worrying about returning values:
            # self.val, self.next = name, Node(self.val, self.next)
        curr = self
        while True:    
            if not curr.next:
                curr.next = Node(name, None)
                break
            else:
                if curr.val.upper() < up < curr.next.val.upper():
                    curr.next = Node(name, curr.next)
                    break
                else:
                    curr = curr.next
        return self
    def __repr__(self):
        return "Node({0.val}, {0.next!r})".format(self)

head = Node("Adam", None)
head = head.add("Aardvark")
head = head.add("Bob")
print(head)
# Node(Aardvark, Node(Adam, Node(Bob, None)))