我知道我们可以通过创建新节点并使用节点引用来更改元素位置。如何仅通过玩节点引用来更改元素位置而不创建或删除节点?非常感谢!
public class LinkedList<E extends Comparable<E>> implements Iterable<E>
{
private Node head; // reference to the first node
private int N; // number of elements stored in the list
private class Node
{
public E item;
public Node next;
public Node()
{
item = null; next = null;
}
public Node(E e, Node ptr)
{
item = e; next = ptr;
}
}
public boolean Move(E e){
Node current=head;
while(current !=null){
if(e.equals(current.item)){
System.out.println("True");
return true;
*****Then how to move this node to the front? Without creating and deleting nodes******
}
current=current.next;
}
System.out.println("False");
return false;
您的算法应该是这样的
int count = 1; // change to 0 if zero-indexed
Node p = null; // previous
Node n = head; // current
while(count < k) {
if(n.next != null) {
p = n;
n = n.next;
count++;
} else
break;
}
if(count == k){
p.next = n.next;
n.next = head;
head = n;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句