请考虑以下我的代码,以便在假定链表已排序的情况下在特定位置插入节点:
package datastructures;
public class Link {
int data;
Link next;
public Link(int d){
this.data = d;
}
public void displayLink(){
System.out.println(data + " ");
}
public static class LinkList {
Link first;
public void insertFirst(int x) {
Link newLink = new Link(x);
newLink.next = first;
first = newLink;
}
public Link deleteFirst() {
Link temp = first;
first = first.next;
return temp;
}
public void displayList() {
Link current = first;
while (current != null) {
current.displayLink();
current = current.next;
}
}
public void insertNodeAtParticularLocation(int x){
Link previous = first;
Link current = first.next;
if (first == null){
// if node doesn't exist in the
// linkedlist then just create a new node
Link newNode = new Link(x);
} else if (x < first.data) {
// Else if the value that needs to be inserted
// is less than the first element, then insert
// it at the very beginning
Link newNode = new Link(x);
newNode.next = first;
first = newNode;
} else {
while(current.data > x){ // In case of21,22,23,27 ; If x = 24 , current should stop at 27
previous = current;
current = current.next;
Link newNode = new Link(x);
previous.next = newNode;
newNode.next = current;
}
}
}
}
public static void main(String[] args) {
LinkList addElements = new LinkList();
addElements.insertFirst(21);
addElements.insertFirst(22);
addElements.insertFirst(23);
addElements.insertFirst(27);
addElements.insertFirst(29);
System.out.println("Display Original Elements");
addElements.displayList();
addElements.insertNodeAtParticularLocation(24);
System.out.println("Display Elements after First Modification");
addElements.displayList();
}
}
我的insertNodeAtParticularLocation()
方法有些问题。
问题1:
当我尝试添加时24
,它仍会添加到列表的末尾,而不是在应该位于具有value的节点之后的指定位置23
。
问题2:
另外,我尝试添加另一个10
我希望在开始时添加的值,但是它覆盖了最后一个元素27,并在该位置被添加。请让我知道我在做什么错。
存在多个问题:
insertFirst
将早先插入的元素向后推。如果要在main中使用insertFirst,则需要颠倒顺序:
addElements.insertFirst(29);
addElements.insertFirst(27);
addElements.insertFirst(23);
addElements.insertFirst(22);
addElements.insertFirst(21);
有一些问题insertNodeAtParticularLocation
:
我写insertNodeAtParticularLocation
如下:
public void insertNodeAtParticularLocation(int x) {
if (first == null || x < first.data) {
// if the value that needs to be inserted
// is less than the first element, or it does not exist,
// then insert it at the very beginning
insertFirst(x);
} else {
Link previous = first;
Link current = first.next;
while(current != null && current.data > x) {
previous = current;
current = current.next;
}
Link newNode = new Link(x);
previous.next = newNode;
newNode.next = current;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句