问题
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;
}
}
}
This is what I have for this. I'm having troubles to insert the newElement before intended element. Can't seem to figure out the syntax for it. I've been tinkering with it for a while and the best I could get was for it to insert after the element like it currently does
Any help would be greatly appreciated
回答1:
In case of a single linked list, you will need two temporary nodes:
MyNode<E> current
that will represent the current node in the single linked list.MyNode<E> prev
that will represent a node before the current node in the single linked list.
Then, you have to add the new node between these nodes. If you don't have the prev
node, then when setting the current
node as the next node of the new node, then all the nodes before current
will be lost.
This is how your code would look like:
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;
}
}
}
回答2:
The trick is to memorise the previous node.
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;
}
回答3:
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
回答4:
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();
}
Create a new node called previous-node, and keep track of current element. In my code, if the current element matches the value of the node variable, we add a new node before it.
来源:https://stackoverflow.com/questions/26365140/how-to-insert-and-element-before-another-in-a-linked-list