Change Element Position in linkedList

I know we can change element position by creating new node and play with node references. How can i change element position without creating or deleting node, only by play with node references? many thanks!

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

2 Answers

your algorithm should be something like this

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest