• 0

[JAVA] Interleaving Two Linked Lists


Question

http://raider.muc.edu/~pelletjp/mergeList.htm

I've been working on this problem and need some help getting it started.

public void interleavingLists(LinkedList X, LinkedList Y)
{
		 while(x != null && y != null)
			  { // test here, then merge according to test
				  }
} // interleaving list

Can anyone help me with this problem, or get me pointed in the right direction?




			
		
Link to comment
https://www.neowin.net/forum/topic/445029-java-interleaving-two-linked-lists/
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Just iterate through X and insert the head of Y between X and X.next. Then remove the head of Y.

Stop looping once you've either reached the end of X or Y. Whether |X| < |Y| or |X| >= |Y|, you'll always have the slack hanging off the end of the interleaved part.

  • 0

What about this....

public void interLeaveLists (LinkedList x, LinkedList y) {
	Link firstX = x.getFirst();
	Link firstY = y.getFirst();
	Link nextX = firstX.next;
	if (x.getSize() &lt;= y.getSize()) {
		Link nextY;
		while (firstX.next != null) {
			nextY = firstY.next;
			firstY.next = firstX.next;
			firstX.next = firstY;
			firstX = firstY.next;
			firstY = nextY;
		}
	}
	else {
		Link nextY;
		while (firstY.next != null) {
			nextY = firstY.next;
			firstY.next = firstX.next;
			firstX.next = firstY;
			firstX = firstY.next;
			firstY = nextY;
		}
	}
}

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.