【问题标题】:change element position in linkedList更改linkedList中的元素位置
【发布时间】:2015-05-08 19:21:48
【问题描述】:

我知道我们可以通过创建新节点并使用节点引用来更改元素位置。我怎样才能改变元素位置不创建或删除节点,只玩节点引用?非常感谢!

    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;

【问题讨论】:

  • 您需要将节点移动到哪里?
  • 请向我们展示您的代码。
  • @SashaSalauyou 我正在尝试编写一个采用k-index 并移动到linkedList 前面的方法。谢谢!
  • 那么到目前为止你自己想出了什么?
  • 按相关顺序将节点添加到新的LinkedList

标签: java linked-list


【解决方案1】:

你的算法应该是这样的

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

【讨论】:

  • 感谢维哈尔!对不起,我没有足够的代表来投票给你
  • 接受@John 的答案
【解决方案2】:
public void changeOrder(){     
    //keep the pointer to next element of the first
    ListNode current=front.next;
    //make first point to the next element
    first.next=current.next;
    current.next=first;
    first=current;
    //the current one was moved one step back and it points to first.
    //change the position
    current=current.next;
    while(current.next!=null && current.next.next!=null){
        ListNode temp = current.next.next;
        current.next.next=temp.next;
        temp.next=current.next;
        current.next=temp;
        current=temp.next;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多