In: Computer Science
Given a singly linked list that contains a sequence of integers, write a method that loop through each elements in this singly linked list with O(n) time complexity, and let each elements multiply 6, return the result.
code needed in java! thanks in advance!
Given:-
-Given a singly linked list that contains a sequence of integers,
-write a method that loop through each element in this singly linked list with O(n) time complexity, and let each element multiply 6,
-return the result.
Explanation:-
import java.io.*;
public class LinkedList { 
 Node head;                     // head of the list 
 // Linked list Node. 
 // This inner class is made static 
 // so that main() can access it 
 
 static class Node { 
     int data; 
     Node next; 
     // Constructor 
     Node(int d) 
     { 
         data = d; 
         next = null; 
     } 
 } 
 
 // Method to insert a new node 
 public static LinkedList insert(LinkedList list, int data) 
 { 
     // Create a new node with given data 
     Node new_node = new Node(data); 
     new_node.next = null; 
     // If the Linked List is empty, 
     // then make the new node as head 
     if (list.head == null) { 
         list.head = new_node; 
     } 
     else { 
         // Else traverse till the last node 
         // and insert the new_node there 
         Node last = list.head; 
         while (last.next != null) { 
             last = last.next; 
         } 
         // Insert the new_node at last node 
         last.next = new_node; 
     } 
     // Return the list by head 
     return list; 
 } 
 // Method to print the LinkedList and multiply
 public static void printList(LinkedList list) 
 { 
     Node currNode = list.head; 
     System.out.print("LinkedList with multiply 6 :- "); 
     
     // Traverse through the LinkedList with o(n) complexity...
     while (currNode != null) 
     { 
                       // Print the data at the current node with multiply each number with 6 and print.
         System.out.print((currNode.data)*6 + " "); 
         
         // Go to next node 
         currNode = currNode.next; 
     } 
 } 
 // main method
 public static void main(String[] args) 
 { 
     /* Start with the empty list. */
     LinkedList list = new LinkedList(); 
     // Insert the values 
     list = insert(list, 1); 
     list = insert(list, 2); 
     list = insert(list, 3); 
     list = insert(list, 4); 
     list = insert(list, 5); 
     list = insert(list, 6); 
     list = insert(list, 7); 
     list = insert(list, 8); 
     printList(list);  //print list  
 } 
} 
Output:-
