Question

public class LinkedList {          // The LinkedList Node class    private class Node{...

public class LinkedList {
  
  
   // The LinkedList Node class
   private class Node{
      
       int data;
       Node next;
      
       Node(int gdata)
       {
           this.data = gdata;
           this.next = null;
       }
      
   }
  
   // The LinkedList fields
   Node head;
  
   // Constructor
   LinkedList(int gdata)
   {
       this.head = new Node(gdata);
   }
  
   public void Insertend(int gdata)
   {
       Node current = this.head;

       while(current.next!= null)
       {
           current = current.next;
       }
      
       Node newnode = new Node(gdata);
       current.next = newnode;
      
   }
  
   public void Listprint()
   {
       Node current = this.head;

       while(current!= null)
       {
           System.out.print(current.data + " ");
           current = current.next;
       }
      
       System.out.println();
      
   }
  
  
  
   public void Listsort(Node start)
   {
   // Complete this method to sort a Linked list
   // Return the first node in the sorted list
   // Feel free to change the method type, add/remove parameters
   // Full credit (30 points) will be awarded for an algorithm that is O(nlog n).
   // Algorithms that are O(n^2) slower will be scored out of 10 points.
  

  
  
      
   }
  
   public static void main(String[] args) {
      
       LinkedList exlist = new LinkedList(0);
       exlist.Insertend(1);
       exlist.Insertend(5);
       exlist.Insertend(2);
       exlist.Insertend(7);
       exlist.Insertend(10);
       exlist.Insertend(3);
      
       exlist.Listprint();
       //output: 0 1 5 2 7 10 3
       exlist.Listsort(exlist.head);
       exlist.Listprint();
       //output should be: 0 1 2 3 5 7 10
      
      
   }
  
  
  

}

Implement Problem 1 in Java.

Note:

Find a file called LinkedList.java in assignment 6 folder.

Complete the method of Listsort().

Test your method in the main method provided following the comments.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

public class LinkedList {

    // The LinkedList Node class

    private class Node {

        int data;

        Node next;

        Node(int gdata) {

            this.data = gdata;

            this.next = null;

        }

    }

    // The LinkedList fields

    Node head;

    // Constructor

    LinkedList(int gdata) {

        this.head = new Node(gdata);

    }

    public void Insertend(int gdata) {

        Node current = this.head;

        while (current.next != null) {

            current = current.next;

        }

        Node newnode = new Node(gdata);

        current.next = newnode;

    }

    public void Listprint() {

        Node current = this.head;

        while (current != null) {

            System.out.print(current.data + " ");

            current = current.next;

        }

        System.out.println();

    }

    public Node merge(Node l, Node r) {

        Node tmp = null;

        // if left node is null return right as null l denotes left linked list is empty

        if (l == null)

            return r;

        if (r == null)

            return l;

        // merge the linked by comparing each value

        // like we merge two sorted arrays

        if (l.data <= r.data) {

            tmp = l;

            tmp.next = merge(l.next, r);

        } else {

            tmp = r;

            tmp.next = merge(l, r.next);

        }

        return tmp;

    }

    // using recurive approch merge sort

    public Node Listsort(Node start) {

        // if linked list has only one or no nodes

        if (start == null || start.next == null) {

            return start;

        }

        // find the middle like we generally do in merge sort for arrays

        Node middle = findMiddle(start);

        // temporarly storing next of middle middle node

        Node middleNext = middle.next;

        // and making next of middle to null to divide the linked list

        middle.next = null;

        // Recursively diving linked it

        // first part

        Node l = Listsort(start);

        // second part

        Node r = Listsort(middleNext);

        // merge the linked

        Node after_sorting = merge(l, r);

        return after_sorting;

    }

    // using fast and slow pointer concept to find middle of the linked in O(n/2)

    // time complexity

    // when the fast pointer reaches the end Node the slow pointer is at the middle

    public static Node findMiddle(Node head) {

        if (head == null)

            return head;

        Node slow = head, fast = head;

        while (fast.next != null && fast.next.next != null) {

            slow = slow.next;

            fast = fast.next.next;

        }

        return slow;

    }

    public static void main(String[] args) {

        LinkedList exlist = new LinkedList(0);

        exlist.Insertend(1);

        exlist.Insertend(5);

        exlist.Insertend(2);

        exlist.Insertend(7);

        exlist.Insertend(10);

        exlist.Insertend(3);

        exlist.Listprint();

        // output: 0 1 5 2 7 10 3

        exlist.Listsort(exlist.head);

        exlist.Listprint();

        // output should be: 0 1 2 3 5 7 10

    }

}

OUTPUT:

Please upvote if you like my answer and comment below if you have any queries.

Add a comment
Know the answer?
Add Answer to:
public class LinkedList {          // The LinkedList Node class    private class Node{...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList()...

    P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList() { header = null; } public final Node Search(int key) { Node current = header; while (current != null && current.item != key) { current = current.link; } return current; } public final void Append(int newItem) { Node newNode = new Node(newItem); newNode.link = header; header = newNode; } public final Node Remove() { Node x = header; if (header != null) { header...

  • Question - modify the code below so that for a node, the value of every node...

    Question - modify the code below so that for a node, the value of every node of its right subtree is less the node, and the value of each node of its left subtree is greater than the node. - create such a binary tree in the Main method, and call the following method:  InOrder(Node theRoot),  PreOrder(Node theRoot),  PostOrder(Node theRoot),  FindMin(),  FindMax(),  Find(int key) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

  • //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args )...

    //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args ) { Scanner in = new Scanner( System.in ); LinkedList teamList = new LinkedList(); final int TEAM_SIZE = Integer.valueOf(in.nextLine()); for (int i=0; i<TEAM_SIZE; i++) { String newTeamMember = in.nextLine(); teamList.append(newTeamMember); } while (in.hasNext()) { String removeMember = in.nextLine(); teamList.remove(removeMember); }    System.out.println("FINAL TEAM:"); System.out.println(teamList); in.close(); System.out.print("END OF OUTPUT"); } } =========================================================================================== //PoD import java.util.NoSuchElementException; /** * A listnked list is a sequence of nodes with...

  • When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses...

    When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Any suggestions? public class LinkedList<T> {    Node<T> itsFirstNode;    Node<T> itsLastNode;    private int size;    public LinkedList() {        itsFirstNode = null;        itsLastNode = null;          size = 0;    }    public Iterator<T> getIterator() {        return new Iterator(this);    }    // THIS WILL NEED...

  • Complete the implementation of the method replace: public class SinglyLinkedList private Node head, public SinglyLinkedListo this(null) public SinglyLinkedList(Node head) [ this.head -head public Nod...

    Complete the implementation of the method replace: public class SinglyLinkedList private Node head, public SinglyLinkedListo this(null) public SinglyLinkedList(Node head) [ this.head -head public Node getHeado return head public void setHead(Node head) [ head: this. head Method that creates a Node containing 'item' @param item Value to be added this.headnew Node(item, this.head) * and adds it as the first element in the list *I public void add(int item) Method that finds the node at the given index d replaces its value...

  • C++ program: Convert the classes to template classes #include <iostream> #include <string> using namespace std; class Node { private: int data; Node* next; public: Node(int...

    C++ program: Convert the classes to template classes #include <iostream> #include <string> using namespace std; class Node { private: int data; Node* next; public: Node(int data) { this->data=data; this->next = 0; } int getData(){return data;} Node* getNext(){return next;} void setNext(Node* next){this->next=next;} }; class LinkedList { private: Node* head = 0; public: int isEmpty() {return head == 0;} void print() { Node* currNode = head; while(currNode!=0) { cout << currNode->getData() << endl; currNode = currNode->getNext(); } } void append(int data) {...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • could somone please help me to complete this ! public class MyLinkedList<AnyType> { private Node<AnyType> head,...

    could somone please help me to complete this ! public class MyLinkedList<AnyType> { private Node<AnyType> head, tail; private int size; public MyLinkedList() { this.head = null; this.tail = null; this.size = 0; } //1.Insert a node at the end of the list public void insert(AnyType data) { Node<AnyType> newNode = new Node(); newNode.data = data; if (head == null) { head = newNode; tail = newNode; head.next = null; tail.next = null; } else { tail.next = newNode; tail =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT