[英]Insert into Doubly LinkedList
我正试图以相反的顺序将字符串插入到双向链表中。 但是我不确定如何保持相反的插入顺序。
这是我的下面的代码。
theList.insertReverseLexicographicalOrder("B");
theList.insertReverseLexicographicalOrder("A");
theList.insertReverseLexicographicalOrder("H");
theList.insertReverseLexicographicalOrder("D");
theList.insertReverseLexicographicalOrder("E");
public void insertReverseLexicographicalOrder(String dd) {
Link newLink = new Link(dd);
if (isEmpty()){
last = newLink;
}
first.previous = newLink;
}
newLink.next = first;
first = newLink;
}
任何建议将基于我的解决方案提供一些代码。
好吧,您假设它已经处于相反的顺序,因此您将需要某种循环,直到找到它应该去的地方。
Z,Y,X,W,L,K,A
如果要插入M,则应循环播放直到找到L(在字典上大于M),然后将其插入。 由于节点具有先前的指针,因此插入并不难,您可以自己弄清楚
如何将节点插入链表:
first
, last
以及一些next
和previous
字段,具体取决于必须在哪里插入 if (first == null) {
// the list is empty so far
} else
要找到位置,首先将数据与第一个节点的数据进行比较,以查看是否必须将其插入第一个节点之前。
if (newLink.iData.compareTo(first.iData) > 0) {
// put newLink before first
} else {
您必须专注于某些列表节点。 从头开始按照列表进行操作,直到到达插入点:
Link focus = first; // focus first node
while(focus.next != null && newLink.iData.compareTo(focus.next.iData) < 0) {
focus = focus.next;
}
// now you have to insert the new value behind focus, left as exercise
if (focus.next == null) {
// newLink becomes the last node in the list
} else {
// newLink has to be inserted between focus and focus.next
}
}
然后插入。 当心边缘盒,在前端和后端插入的内容略有不同。
您需要浏览列表以比较每个元素。 当您找到要插入的元素之后的元素时,请停止。 我建议您在节点类中实现compareTo方法: http : //www.javapractices.com/topic/TopicAction.do? Id =10并使用它进行比较
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.