Jump to content

  • Log In with Google      Sign In   
  • Create Account


Exchange the position of two Nodes [Java]


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 Cuajin   Members   -  Reputation: 155

Like
0Likes
Like

Posted 06 April 2012 - 01:21 PM

I’m trying to exchange the position of two nodes a and b.

I have the Node class that helps me create a list.
class Node
{  
   E info;	
   Node next;

   Node (E x)  
   {
	 next = null;  
	 info = x;	  
   }
}

Then I have class List.
public class List<E>
{
  private Node headNode;
  // some methods like addToList(). They work.

// Problem here!
  public void exchangeNodes(int a, int b)
   {
	 Node lead = head;
	
	 while (lead != null)
	 {
		// here I wrote a bunch of noob code that if you looked at it your eyes would hurt.
	 }
   }

TestClass
public class TestClass
{
   List myList = new List();
   // populating the list with strings.
   myList.add("a");
   myList.add("b");
   myList.add("c");
   myList.add("d");
   myList.add("e");
   myList.add("f");
   myList.add("g");

   myList.exchange(2, 5); // giving it position numbers to exchange.
}

The big problem is I can't get it to switch the Node's position on the list without destroying Nodes (I lose the reference to pointers when I switch). Clearly Nodes and me don't like each other Posted Image

From the TestClass I want to say exchange what's on position 2 with what is on position 5.

Please help.

Sponsor:

#2 FLeBlanc   Crossbones+   -  Reputation: 3061

Like
0Likes
Like

Posted 06 April 2012 - 03:53 PM

If you want to numerically index a list like that, you need to start from the beginning of the list, incrementing a counter and moving to the Next node each time through the loop until the counter reaches the index value or the end of the list is reached (raising an out_of_bounds error). Once you have found the nodes for each of the given indices, it is a simple matter to swap the values of info for the two nodes.

Is exchanging two nodes an operation that you are going to be performing frequently? If so, using a linked list could hurt your performance.

It is always beneficial to analyze the most common use-cases for your data structures, and choose structures appropriately. In this case, indexing the structure via a numerical index is an example of a random-access usage, and linked-lists are notoriously poor for random-access since, as you can see, you have to iterate through the list with each access. Whereas, with an array type, the random-access is a simple array indexing operation. Of course, you also have to take into account your other usage patterns, which might offset this disadvantage.

#3 Cuajin   Members   -  Reputation: 155

Like
0Likes
Like

Posted 06 April 2012 - 04:32 PM

I don't plan to use the exchangeNodes as much. I was originally thinking ArrayList but it was too slow for the other operations.

I could swap the info parts, but I actually need to swap the nodes (might also be good to learn to actually swap the nodes because I need a similar thing for another project, a game involving maple trees).

I am trying the trailer / leader approach to swap the nodes but I just ended up creating a queue during execution which is definitely bad since all I wanted was to swap nodes.

#4 Kyan   Members   -  Reputation: 395

Like
0Likes
Like

Posted 06 April 2012 - 05:40 PM

First, there's nothing wrong with a bunch of "noob code that would make our eyes hurt". If you don't show us what you tried, we can't help you make it work. That said, off the top of my head you'd do something like:
  • Ensure that a and b are valid indexes. There is no point in traversing the list if the indexes are either wrong (< 0) or out of bounds (>= list.size()).
  • Traverse the list and determine where your nodes actually are. If you're not going to determine which of a or b is smaller ahead of time then you need to keep track of where you are in relation to the indexes you are searching for. Keep in mind that your placement should be the parent of the first node you need, while your temporary swap should be the node itself. Once you've found both nodes (remember, parents only) you can perform a simple swap and fix your links without needing to traverse again.
    • You should end up with three variables: firstParent, temp (= firstParent.next), and secondParent.
  • Make sure you handle all the boundary cases for when either a or b indicate the head or the tail of your list, which will result in specific, faster implementations (for obvious reasons).

Also, if you've already implemented remove() and insert(int) you can simply use those instead. Technically, that isn't particularly performant but if you're not going to use exchangeNodes(int, int) all that frequently then it's something to consider.

#5 rip-off   Moderators   -  Reputation: 6880

Like
0Likes
Like

Posted 10 April 2012 - 04:23 PM

I was originally thinking ArrayList but it was too slow for the other operations.

I highly doubt this. Linked lists look great in theory, but their memory overhead (which is particularly bad in Java) and their cache incoherency will almost always cost more than a contiguous dynamic array implementation.

I could swap the info parts, but I actually need to swap the nodes

If your code depends on the difference, then it is extremely brittle. The existence of nodes in a linked list is an implementation detail that shouldn't be directly exposed. It is also harder to maintain such code. Finally, it involves more work and so is less efficient than just swapping the data references.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS