请考虑我的代码,以便在特定位置插入节点,假设链表已排序:
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
时,它仍然会添加到列表的末尾,而不是添加到应该位于值为23
的节点之后的指定位置。
问题#2:
另外,我尝试添加另一个值10
,我希望在开头添加它,但是它覆盖了最后一个27的元素,并添加了它的位置。请让我知道我做错了什么。
答案 0 :(得分:0)
存在多个问题:
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;
}
}