[英]How to insert a node to a list with given data and maintain the list to be sorted in java
How do i add 100 to the linked list while keeping it sorted? 如何在链接列表中添加100并保持排序? I know i have to add an item to the front of a single-linked list and make it point to the first node of the list but am having much trouble in finding ways to start this problem off.
我知道我必须在单链接列表的前面添加一个项目,并使它指向列表的第一个节点,但是在寻找解决此问题的方法时遇到了很多麻烦。
IntegerNode n3 = new IntegerNode(9, null);
IntegerNode n2 = new IntegerNode(5, n3);
IntegerNode head = new IntegerNode(1, n2);
IntegerNode curr;
IntegerNode prev;
//print all the items in the linked-list
for(curr = head; curr!=null; curr = curr.getNext()) {
System.out.println(curr.getItem());
}
int data = 100;
//insert an node to the list with the given data, and maintain the list to be sorted
}
}
The following insert
method should be a start: 以下
insert
方法应作为一个开始:
public void insert(int val){
if(this.head==null){ //empty
this.head = new IntegerNode (val);
this.head.setNext(null);
return;
}
IntegerNode prev = null;
IntegerNode curr = this.head;
IntegerNode newNode = new SLLNode(val);
while(curr!=null && curr.getVal()<val){
prev = curr;
curr = curr.getNext();
}
if(prev==null){//new element to be placed at first
newNode.setNext(curr);
this.head = newNode;
}
else if(curr==null){// new element to be placed at end
newNode.setNext(null);
prev.setNext(newNode);
}else{ //intermediate position
newNode.setNext(curr);
prev.setNext(newNode);
}
}
Steps are as follows: 步骤如下:
prev
is null, that menas the value we are inserting is smaller than all values currently in list and should be placed at the first. prev
为null,则表示我们要插入的值小于当前列表中的所有值,应放在第一个值上。 curr
is null, that means we have reached the end of the list iterating and our value is larger than all the nodes currently in list.So we set the node at last. curr
为null,则意味着我们已经迭代到列表的末尾,并且我们的值大于列表中当前的所有节点,因此我们最后设置了该节点。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.