SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Linked Lists
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

Write a method called transferFrom that accepts a second linked list as a parameter and that moves values from the second list to this list. You are to attach the second list’s elements to the end of this list. You are also to empty the second list. For example, suppose two lists called list1 and list2 store [8, 17, 2, 4] and [1, 2, 3] respectively. The call of list1.transferFrom(list2); should change list1 to [8, 17, 2, 4, 1, 2, 3] and list2 to an empty list, []. The order of the arguments matters; list2.transferFrom(list1); should change list1 to an empty list, [] , and list2 to [1, 2, 3, 8, 17, 2, 4] . Either of the two lists could be empty, but you can assume that neither list is null. You are not to create any new nodes. Your method should simply change links of the lists to join them together.

Add the above method to the LinkedIntList class from this chapter.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of transferFrom method:

public void transferFrom(LinkedIntList other)
	{
		if(front == null && other.front == null)
			return;

		if(front == null)
		{
			front = other.front;
			other.front = null;
		}
		else
		{
			ListNode current = front;
			while(current.next != null)
			{
				current = current.next;
			}

			current.next = other.front;
			other.front = null;
		}
	}

 

0 0

Discussions

Post the discussion to improve the above solution.