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

Question

Write a method called doubleList that doubles the size of a list by appending a copy of the original sequence to the end of the list. For example, if a variable list stores the values [1, 3, 2, 7] and we make the call of list.doubleList(); then after the call it should store [1, 3, 2, 7, 1, 3, 2, 7] . Notice that the list has been doubled in size by having the original sequence appear twice in a row. You may not make assumptions about how many elements are in the list. You may not call any methods of the class to solve this problem. If the original list contains n nodes, then you should construct exactly n nodes to be added. You may not use any auxiliary data structures such as arrays or ArrayList s to solve this problem. Your method should run in O(n) time where n is the number of nodes in the list.

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of doubleList method:

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

		int count = 0;
		ListNode current = front;
		while(current.next != null)
		{
			current = current.next;
			count++;
		}

		ListNode temp = front;
		while(temp != null && count >= 0)
		{
			current.next = new ListNode(temp.data);
			current = current.next;

			temp = temp.next;
			count--;
		}
	}

 

0 0

Discussions

Post the discussion to improve the above solution.