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

Question

Write a method called removeRange that accepts a starting and ending index as parameters and removes the elements at those indexes (inclusive) from the list. For example, if a variable list stores the values [8, 13, 17, 4, 9, 12, 98, 41, 7, 23, 0, 92] , the call of listRange.removeRange(3, 8); should remove values between index 3 and index 8 (the values 4 and 7 ), leaving the list of [8, 13, 17, 23, 0, 92] . The method should throw an IllegalArgumentException if either of the positions is negative. Otherwise you may assume that the positions represent a legal range of the list (0 <= start <= end < size).

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of removeRange method:

public void removeRange(int start, int end)
	{
		if(start < 0 || end < 0)
			throw new IllegalArgumentException();

		ListNode previous = null;
		ListNode current = front;
		int index = 0;

		while(current != null && index < start)
		{
			previous = current;
			current = current.next;
			index++;
		}

		while(current != null && index <= end)
		{
			if(previous == null)
			{
				front = front.next;
				previous = null;
				current = front;
			}
			else
			{
				previous.next = current.next;
				current = previous.next;
			}

			index++;
		}
	}

 

0 0

Discussions

Post the discussion to improve the above solution.