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

Question

Write a method called rotate that moves the value at the front of a list of integers to the end of the list. For example, if a variable called list stores the values [8, 23, 19, 7, 45, 98, 102, 4] , then the call of list.rotate(); should move the value 8 from the front of the list to the back of the list, changing the list to store [23, 19, 7, 45, 98, 102, 4, 8] . If the method is called for a list of 0 elements or 1 element, it should have no effect on the list. You may not construct any new nodes to solve this problem nor change any of the data values stored in the nodes. You must solve the problem by rearranging the links of the list.

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of rotate method:

public void rotate()
	{
		if(front == null)
			return;
		
		ListNode current = front;
		ListNode firstNode = current;

		while(current.next != null)
		{
			current = current.next;
		}

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

 

0 0

Discussions

Post the discussion to improve the above solution.