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

Question

Write a method called shift that rearranges the elements of a list of integers by moving to the end of the list all values that are in odd-numbered positions and otherwise preserving list order. For example, suppose that a variable list stores the values [10, 31, 42, 23, 44, 75, 86] . The call of list.shift(); should rearrange the list to store [10, 42, 44, 86, 31, 23, 75] . It doesn’t matter whether the value itself is odd or even; what matters is whether the value appears in an odd index (index 1, 3, 5, etc). Also notice that the original order of the list is otherwise preserved. You may not construct any new nodes nor use any auxiliary data structures to solve this problem. You also may not change any data fields of the nodes; you must solve this problem by rearranging the links of the list.

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of shift method:

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

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

 

0 0

Discussions

Post the discussion to improve the above solution.