public void insertElementBefore(E element, E newElement) {
MyNode<E> current = head;
if (head != null) {
while (current != null) {
if (current.data.equals(element)) {
MyNode<E> n = new MyNode<E>(newElement);
n.next = current.next;
current.next = n;
return;
}
current = current.next;
}
}
}
这就是我对此的看法。我在预期的元素之前插入newElement有麻烦。似乎无法弄清楚它的语法。我已经修了好一会儿,我能得到的最好的就是它像现在一样插入元素之后
非常感谢任何帮助
答案 0 :(得分:2)
如果是单个链接列表,则需要两个临时节点:
MyNode<E> current
代表单个链接列表中的当前节点。MyNode<E> prev
将代表单个链接列表中当前节点之前的节点。然后,您必须在这些节点之间添加新节点。如果您没有prev
节点,那么在将current
节点设置为新节点的下一个节点时,current
之前的所有节点都将丢失。< / p>
这就是你的代码的样子:
public void insertElementBefore(E element, E newElement) {
MyNode<E> current = head;
//check here
MyNode<E> prev = null;
if (head != null) {
while (current != null) {
if (current.data.equals(element)) {
MyNode<E> n = new MyNode<E>(newElement);
n.next = current;
//check here
if (prev != null) {
prev.next = n;
}
return;
}
//check here
prev = current;
current = current.next;
}
}
}
答案 1 :(得分:1)
诀窍是记住上一个节点。
MyNode<E> current = head;
MyNode<E> previous = null;
while (current != null && !current.data.equals(element)) {
return;
}
previous = current;
current = current.next;
}
MyNode<E> n = new MyNode<>(newElement);
n.next = current;
if (previous == null) {
head = n;
} else {
previous.next = n;
}
答案 2 :(得分:0)
void Insert_Before(int num)
{
Node *x=new Node();
x->data=num;
if (head==NULL) {
x->next=head;
head=x;
} else {
int c=1;
cout<<"Element before which insertion has to take place:";
cin>>n;
Node *temp=head;
Node *temp1;
//check whether the element is present or not
while (temp->data!=n) { //if present
temp=temp->next;
c=c+1; //finds the position of the element n
}
x->next=temp;
if (c==1) {
head=x;
} else {
int i=1;
while (i<=c-1) {
temp1=temp1->next;
i=i+1;
}
temp1->next=x;
}
}
} //Insert_Before
答案 3 :(得分:0)
Node n=headNode;
Node prev=null;
while(n!=null){
if(n.getData()==node){
Node newNode=new Node(data);
prev.setNext(newNode);
newNode.setNext(n);
break;
}
else{
prev=n;
n=n.getNext();
}
}
if(n.getNext()==null){
Node newNode= new Node(data);
prev.setNext(newNode);
newNode.setNext(null);
}
System.out.println("New LinkedList after insert before is:");
printList();
}
创建一个名为previous-node的新节点,并跟踪当前元素。在我的代码中,如果当前元素与节点变量的值匹配,我们在它之前添加一个新节点。