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

Question

Write a method called removeEvens that removes the values in even-numbered indexes from a list, returning a new list that contains those values in their original order. For example, consider a variable list1 that stores the values [8, 13, 17, 4, 9, 12, 98, 41, 7, 23, 0, 92] and imagine that the following call is made:

LinkedIntList list2 = list1.removeEvens();

After the call, list1 should store [13, 4, 12, 41, 23, 92] and list2 should store [8, 17, 9, 98, 7, 0] . You may not call any methods of the class other than the constructor to solve this problem. You may not create any new nodes nor change the values stored in data fields to solve this problem. You must solve it by rearranging the links of the list.

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of removeEvens method:

public LinkedIntList removeEvens()
	{
		LinkedIntList evensList = new LinkedIntList();						
		ListNode newCurrent = null;
		ListNode previous = null;
		
		int index = 0;		
		ListNode current = front;		
		while(current != null)
		{			
			if(index % 2 == 0)
			{
				if(index == 0)
				{
					evensList.front = front;
					front = front.next;					
					
					newCurrent = evensList.front;
					
					previous = null;
					current = front;
				}
				else
				{
					newCurrent.next = current;
					newCurrent = newCurrent.next;
					
					previous.next = current.next;
					current = previous.next;
				}
			}
			else
			{
				previous = current;
				current = current.next;
			}
			
			index++;
		}
		
		if(newCurrent != null)
			newCurrent.next = null;
				
		return evensList;		
	}

 

0 0

Discussions

Post the discussion to improve the above solution.