Write a method stretch that stretches a linked list of integers by a specified i
ID: 3803481 • Letter: W
Question
Write a method stretch that stretches a linked list of integers by a specified integer value amount, so that each node of the list parameter is represented by amount copies of the node in the list that's returned.
The ListNode class will be accessible when your method is tested:
public class ListNode { int info;
ListNode next;
ListNode(int x){ info = x; }
ListNode(int x, ListNode node){
info = x;
next = node; }
}
Skeleton Code Provided:
public class ListStretch {
public ListNode stretch (ListNode list, int amount){
// replace statement below with code you write
return null;
}
}
For example
returns [1,1,2,2,3,3] since each value is represented by two values in the list returned.
returns [] since an empty/null list has no nodes that are represented in the return list
returns [5,5,5,5,6,6,6,6,8,8,8,8,9,9,9,9]
Explanation / Answer
HI, Please find my working code.
Please let me know in case of any issue.
class ListNode { int info;
ListNode next;
ListNode(int x){ info = x; }
ListNode(int x, ListNode node){
info = x;
next = node; }
}
public class ListStretch {
public ListNode stretch (ListNode list, int amount){
// replace statement below with code you write
ListNode current = list;
ListNode nextNode = null;
while(current != null){
nextNode = current.next;
ListNode first = current;
ListNode last = first;
// creating copy
for(int i=1; i<amount; i++){
last.next = new ListNode(first.info);
last = last.next;
}
last.next = nextNode;
current = nextNode;
}
return list;
}
public static void main(String[] args) {
ListStretch l = new ListStretch();
ListNode node = new ListNode(3);
node.next = new ListNode(4);
node.next.next = new ListNode(1);
node = l.stretch(node, 3);
ListNode temp = node;
while(temp != null){
System.out.print(temp.info+" ");
temp = temp.next;
}
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.