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:11 | ISBN:9780136091813 | Edition: 2

Question

Write a method called split that rearranges the elements of a list so that all of the negative values appear before all of the nonnegatives. For example, suppose a variable list stores the values [8, 7, -4, 19, 0, 43, -8, -7, 2] .

The call of list.split(); should rearrange the list to put the negatives first: [-4, -8, -7, 8, 7, 19, 0, 43, 2] . It doesn’t matter what order the numbers are in, only that the negatives appear before the nonnegatives, so this is only one possible solution. You must solve the problem by rearranging the links of the list, not by swapping data values or creating new nodes. You also may not use auxiliary structures like arrays or ArrayList s to solve this problem.

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of split method:

public void split()
	{
		if(front == null)
			return;

		int value;
		int index = 0;
		int count = 0;
		
		ListNode current = front;		
		while(current != null)
		{
			if(current.data < 0)
			{
				value = current.data;
				remove(index);
				add(count, value);				
				count = count + 1;
			}

			index = index + 1;
			current = current.next;			
		}
	}

 

0 0

Discussions

Post the discussion to improve the above solution.