我需要修改程序的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);
}
}
任何关于如何按名称按升序插入的伪代码的想法都会非常棒,谢谢
答案 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
方法。