java - 更改 linkedList 中的元素位置

标签 java linked-list

我知道我们可以通过创建新节点和使用节点引用来更改元素位置。如何更改元素位置无需创建或删除节点,仅通过使用节点引用?非常感谢!

    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;
}

关于java - 更改 linkedList 中的元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30122096/

相关文章:

c++ - 如何向链表添加内容

c - 在链表中查找或创建元素,而不丢失头

c++ - 为什么我的函数不打印出双向链表中的第一个节点?

比较字符串并将其插入到链接列表

java - 搜索数组的链接列表并删除链接

java - 枚举在 Java 内部是如何表示的?

java - 添加操作按钮 : action_search cannot be resolved or is not a field

javascript - 如何在 spring 中使用 ajax jQuery

java - 接口(interface) java/Android 不能从子 fragment 到父 fragment

Java:KeyLIstener 和 PaintComponent 不合作