4

我在弄清楚如何在 Python 中对单链表进行排序时遇到了一些麻烦。我已经想出了如何创建一个链接列表并将数据推送到它上面,但是我如何以排序格式推送它(在所有数据都推送到它之后不排序)或者只是以任何方式对其进行排序?

客观的

根据用户输入创建一个排序的单链数字列表。程序逻辑:请求一个数字,将该数字添加到排序位置的列表中,打印列表。重复直到他们输入 -1 作为数字。

当前代码

#!/usr/bin/env python

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:
    def __init__(self):
        self.cur_node = None

    def add_node(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = self.cur_node # cant point to ll!
        while node:
            print(node.data)
            node = node.next


def main():
  ll = linked_list()

  num=int(input("Enter a num to push onto the list, -1 to stop: "))
  while num!=-1:
    data=num
    ll.add_node(data)
    num=int(input("Enter a num to push onto the list, -1 to stop: "))

  print("\n")
  ll.list_print()
main()

我真的被困在这里了。预先感谢您的任何帮助!

4

5 回答 5

11

这应该这样做:

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

class LinkedList:
  def __init__(self):
    self.head = None

  def addNode(self, data):
    curr = self.head
    if curr is None:
      n = Node()
      n.data = data
      self.head = n
      return

    if curr.data > data:
      n = Node()
      n.data = data
      n.next = curr
      self.head = n
      return

    while curr.next is not None:
      if curr.next.data > data:
        break
      curr = curr.next
    n = Node()
    n.data = data
    n.next = curr.next
    curr.next = n
    return

  def __str__(self):
    data = []
    curr = self.head
    while curr is not None:
      data.append(curr.data)
      curr = curr.next
    return "[%s]" %(', '.join(str(i) for i in data))

  def __repr__(self):
    return self.__str__()

def main():
  ll = LinkedList()
  num = int(input("Enter a number: "))
  while num != -1:
    ll.addNode(num)
    num = int(input("Enter a number: "))
  c = ll.head
  while c is not None:
    print(c.data)
    c = c.next

>>> main()
Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: 4
Enter a number: 1
Enter a number: -1
1
2
3
4
5
于 2013-10-07T05:52:56.010 回答
3
class Node:
    def __init__(self, data):
        self.data = int(data)
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None    

    def asc_ordered_list(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        temp = self.head
        if temp.data > data:
            new_node.next = temp
            self.head = new_node
            return

        while temp.next:
            if temp.next.data > data:
                break
            temp = temp.next

        new_node.next = temp.next
        temp.next = new_node

    def desc_ordered_list(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        temp = self.head
        if data > temp.data:
            new_node.next = temp
            self.head = new_node
            return

        while temp.next:
             if temp.data > data and temp.next.data < data:
                 break
             temp = temp.next

        new_node.next = temp.next
        temp.next = new_node

    def display_list(self):
        temp = self.head
        while temp is not None:
            print("data = {0}".format(temp.data))
            temp = temp.next

if __name__ == "__main__":
    llist = LinkedList()
    llist.desc_ordered_list(8)
    llist.desc_ordered_list(3)
    llist.desc_ordered_list(1)
    llist.desc_ordered_list(4)
    llist.desc_ordered_list(5)
    llist.desc_ordered_list(7)
    llist.desc_ordered_list(6)
    llist.desc_ordered_list(2) 
    llist.display_list()
于 2019-10-04T01:53:27.987 回答
0

4年后,但我认为这样更容易

 def append(self, value):
    new_node = Node(value)
    if self.head is None:
        self.head = new_node
    else:
        current = self.head
        while current is not None and current.value <= value:
            previous = current
            current = current.next
        if current is self.head:
            aux = self.head
            self.head = new_node
            new_node.next = aux
        else:
            previous.next = new_node
            new_node.next = current
    self.size += 1
于 2021-02-24T20:07:24.743 回答
0
class Solution:
    def sortList(self,node):

        if(node is None):
            return
        temp=node
        while(temp!=None):
            i=temp.next
            while(i!=None):
                if(temp.data>i.data):
                    n=i.data
                    i.data=temp.data
                    temp.data=n
                i=i.next
            temp=temp.next
于 2021-01-27T09:19:16.813 回答
-1

我认为这更短更容易

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

def main():
    nodes = []
    num = int(input("Enter number: "))
    while num != -1:
        nodes.append(Node(num))
        num = int(input("Enter number: "))

    # If list is empty then just end function
    if len(nodes) == 0: 
        return

    # Let python do the sorting
    nodes = sorted(nodes, key=lambda node: node.data)

    # Link the nodes together and print them while you're at it
    for i in range(len(nodes) - 1):
        nodes[i].next = nodes[i + 1]
        print(nodes[i].data)
    # We need to print the last node
    print(nodes[-1].data)
于 2016-05-10T19:06:18.853 回答