在Java中单个链接列表中按升序插入项目

时间:2014-04-02 15:15:10

标签: java insert

我需要修改程序的insert方法,以便按升序将项目插入单链表中。我理解链接列表是什么,但不知道如何按顺序插入项目。这是我目前为止的程序(不是整个程序):

public class SinglySortedLinkedList
{  private Node h;  // list header
    public SinglySortedLinkedList()
    {  h = new Node();  // dummy node
        h.l = null;
        h.next = null;
    }



    public boolean insert(Listing newListing)
    {  Node n = new Node();
        if(n == null) // out of memory
           return false;
        else
        { 
           n.next = h.next;
           h.next = n;
           n.l = newListing.deepCopy();
           return true;

        }
   }

这是测试方法:

public class MainSinglyLinkedList
{ public static void main(String[] args)
 {  SinglySortedLinkedList boston = new SinglySortedLinkedList();
    Listing l1 = new Listing("Bill", "1st Avenue", "123 4567" );
    Listing l2 = new Listing("Al", "2nd Avenue", "456 3232");
    Listing l3 = new Listing("Mike", "3rd Avenue", "333 3333");
    boston.insert(l1);  // test insert
    boston.insert(l2);
    boston.insert(l3);
    boston.showAll();
    l3 = boston.fetch("Mike"); // test fetch of Mike
    System.out.println(l3.toString());
    boston .delete("Al");  // test delete of Al
    boston.showAll();
    boston.update("Mike", l2); // test update of Mike to Al
    boston.showAll();
    System.exit(0);
  }
}

任何关于如何按名称按升序插入的伪代码的想法都会非常棒,谢谢

1 个答案:

答案 0 :(得分:0)

我不想做你的作业,但我会给你提示。如果您有更具体的问题,那么您可能会在SO中找到答案。在不太可能发生的情况下,请随时提出新问题;)

  • 首先,您需要在列表中找到要插入的点,然后在该点插入Node n(包含新的Listing)。这可以使用while循环完成,并将列表作为条件进行比较,用英语表示:
  

虽然当前节点的列表不如列表I   想插入,我继续前进

有关如何在Java中对String进行此类比较,请查看the compareTo method

  • 然后,使用您以前的代码在那里插入n。请参阅下面的注释,了解我对它的评价以及您的虚拟Node

旁注

您正在使用"虚拟节点"列表标题,并始终插入该标题之后。 这可能不是必需的,您可以插入每个新的Node代替h并使其指向前h,这将更清晰,更容易阅读恕我直言。

而不是:

n.next = h.next;
h.next = n;
n.l = newListing.deepCopy();

你可以:

n.next = h; // here n's next points to the former head h
h = n;      // now n in the new head referenced by h
n.l = newListing.deepCopy(); 

这样,您甚至不再需要虚拟节点,null可以设置n.next字段。它还可能会简化您的fetch方法。