排序双链表

时间:2015-11-26 21:59:24

标签: python sorting linked-list

我必须写一个双向链表。 它始终按价格排序(按升序排列)。

必须按价格对列表进行排序,并添加新元素。 该算法有效,但如果我改变对象car1-5中的价格或添加另一个对象,它就不再起作用了。

代码:

class Car:
    def __init__(self, price):
        self.price = price
class Node:
    def __init__(self, car):
    self.data = car
    self.nextNode = None
    self.prevNode = None
class LinkedList:
    head = None
    tail = None
    def addNode(self,car):
    new_node = Node(car)
    ref = self.head
        if self.head is None:
            self.head = self.tail = new_node
        elif ref.prevNode is None:
            if int(new_node.data.price) < int(ref.data.price):
                self.head = ref.prevNode = new_node
                new_node.nextNode = ref
            if int(new_node.data.price)>int(ref.data.price) and     (new_node.data.price)>int(ref.nextNode.data.price):
                new_node.prevNode,  new_node.nextNode, ref.nextNode = ref,     ref.nextNode, new_node
        else:
            while ref is not None:
                if int(new_node.data.price) < int(ref.data.price):
                        if ref.prevNone is None:
                            self.head = new_node
                        else:
                            ref.prevNode.nextNode = new_node
                        ref.prevNode,new_node.prevNode = new_node, ref
                elif ref.nextNode is None:
                    self.tail = new_node
                    ref.nextNode, new_node.prevNode = new_node, ref
                    break
                else:
                    ref = ref.nextNode    
    def fromArray(self, cars):
        for item in cars:
            self.addNode(item)
def init(cars):
    L.fromArray(cars)
L = LinkedList()
car1 = Car(10)
car2 = Car(5)
car3 = Car(3)
car4 = Car(2)
car5 = Car(1)
 /*car6 = Car(33) */
cars = [car1, car2, car3, car4, car5,  /*car6*/]
init(cars)

0 个答案:

没有答案