在Java中以升序在单链表中插入项
我需要修改我的程序的insert方法,以便它以升序将项目插入到单链接列表中。我了解什么是链表,但不知道如何按顺序插入项目。以下是我目前的计划(不是整个计划): 以下是测试仪方法:在Java中以升序在单链表中插入项,java,insert,Java,Insert,我需要修改我的程序的insert方法,以便它以升序将项目插入到单链接列表中。我了解什么是链表,但不知道如何按顺序插入项目。以下是我目前的计划(不是整个计划): 以下是测试仪方法: public class MainSinglyLinkedList { public static void main(String[] args) { SinglySortedLinkedList boston = new SinglySortedLinkedList(); Listing l1 = ne
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);
}
}
任何关于如何按名称升序插入的伪代码的想法都非常棒,谢谢,我不想做你的家庭作业,但我会给你提示。如果你有更具体的问题,你可能会在SO中找到答案。在不太可能的情况下,请随意提出新问题;)
- 首先,您需要在列表中找到要插入的点,然后在该点插入
(包含新的节点n
)。这可以使用列表
循环来完成,并将列表之间的比较作为一个条件,在英语中可以这样说:while
String
s上进行这种比较,请参阅
- 然后,使用前一段代码在那里插入
。请参阅下面的注释,了解我对它和您的虚拟n
节点的看法
节点
来代替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
字段。它还可能简化您的获取方法。为什么不在末尾插入并对集合进行排序(假设您可以实现compareTo功能,这很有意义,但我的教授需要的方式是将其排序,因为它是在之后输入的
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();