Question

In: Computer Science

Without dramatically changing the code please add a basic "linked list in ascending order" (option 7)....

Without dramatically changing the code please add a basic "linked list in ascending order" (option 7). Please leave comments within the code so I can understand what is being done, thank you.

import java.util.Scanner;
/* Class Node */

class Node
{
protected int data;
protected Node link;

public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedList
{
protected Node start;
protected Node end ;
public int size ;

public linkedList()
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty()
{
return start == null;
}
public int getSize()
{
   return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
public void insertAtEnd(int val)
{
Node nptr = new Node(val,null);
size++ ;
if(start == null)
{
   start = nptr;
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
}
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size; i++)
{
   if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
}


ptr = ptr.getLink();
}
size++ ;
}
public void deleteAtPos(int pos)
{   
if (pos == 1)
{
start = start.getLink();
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(null);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
public void display()
   {
System.out.print("\nSingly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ "->");
ptr = start.getLink();
while (ptr.getLink() != null)
{
System.out.print(ptr.getData()+ "->");
ptr = ptr.getLink();

}

System.out.print(ptr.getData()+ "\n");

}

}

import java.util.Scanner;
/* Class SinglyLinkedList */

public class SinglyLinkedList

{

public static void main(String[] args)

{
Scanner scan = new Scanner(System.in);

/* Creating object of class linkedList */

linkedList list = new linkedList();

System.out.println("Singly Linked List Test\n");

char ch;

/* Perform list operations */

do

{

System.out.println("\nSingly Linked List Operations\n");

System.out.println("1. insert at begining");

System.out.println("2. insert at end");

System.out.println("3. insert at position");

System.out.println("4. delete at position");

System.out.println("5. check empty");

System.out.println("6. get size");

int choice = scan.nextInt();

switch (choice)

{

case 1 :

System.out.println("Enter integer element to insert");

list.insertAtStart( scan.nextInt() );

break;

case 2 :

System.out.println("Enter integer element to insert");

list.insertAtEnd( scan.nextInt() );

break;

case 3 :

System.out.println("Enter integer element to insert");

int num = scan.nextInt() ;

System.out.println("Enter position");

int pos = scan.nextInt() ;

if (pos <= 1 || pos > list.getSize() )

System.out.println("Invalid position\n");

else

list.insertAtPos(num, pos);

break;

case 4 :

System.out.println("Enter position");

int p = scan.nextInt() ;

if (p < 1 || p > list.getSize() )

System.out.println("Invalid position\n");

else

list.deleteAtPos(p);

break;

case 5 :

System.out.println("Empty status = "+ list.isEmpty());

break;

case 6 :

System.out.println("Size = "+ list.getSize() +" \n");

break;

   default :

System.out.println("Wrong Entry \n ");

break;

}

/* Display List */

list.display();

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}

}

Solutions

Expert Solution

As per the requirement, below is the method that would convert the list in ascending order. It is well explained inside the code using comments:

// This method will make the linked list in ascending order
    void ascending() {
        Node ptr = start, next = null;
        int tempData;   // to store temp data during operation

        // if list is not empty
        if (!isEmpty()) {
            // keep looping until ptr becomes null,
            // means until whole list is iterated
            while (ptr != null) {
                // next link
                next = ptr.getLink();

                // keep looping until next ptr becomes null
                while (next != null) {
                    // if current node data is greater than next, swap the nodes
                    if (ptr.getData() > next.getData()) {
                        tempData = ptr.getData();
                        ptr.setData(next.getData());
                        next.setData(tempData);
                    }
                    // move next to next position
                    next = next.getLink();
                }
                ptr = ptr.getLink();
            }
        }
    }

Below is the complete code, with changes highlighted in bold:


import java.util.Scanner;

/* Class Node */
class Node {

    protected int data;
    protected Node link;

    public Node() {
        link = null;
        data = 0;
    }

    public Node(int d, Node n) {
        data = d;
        link = n;
    }

    public void setLink(Node n) {
        link = n;
    }

    public void setData(int d) {
        data = d;
    }

    public Node getLink() {
        return link;
    }

    public int getData() {
        return data;
    }
}

class linkedList {

    protected Node start;
    protected Node end;
    public int size;

    public linkedList() {
        start = null;
        end = null;
        size = 0;
    }

    public boolean isEmpty() {
        return start == null;
    }

    public int getSize() {
        return size;
    }

    public void insertAtStart(int val) {
        Node nptr = new Node(val, null);
        size++;
        if (start == null) {
            start = nptr;
            end = start;
        } else {
            nptr.setLink(start);
            start = nptr;
        }
    }

    public void insertAtEnd(int val) {
        Node nptr = new Node(val, null);
        size++;
        if (start == null) {
            start = nptr;
            end = start;
        } else {
            end.setLink(nptr);
            end = nptr;
        }
    }

    public void insertAtPos(int val, int pos) {
        Node nptr = new Node(val, null);
        Node ptr = start;
        pos = pos - 1;
        for (int i = 1; i < size; i++) {
            if (i == pos) {
                Node tmp = ptr.getLink();
                ptr.setLink(nptr);
                nptr.setLink(tmp);
                break;
            }

            ptr = ptr.getLink();
        }
        size++;
    }

    public void deleteAtPos(int pos) {
        if (pos == 1) {
            start = start.getLink();
            size--;
            return;
        }
        if (pos == size) {
            Node s = start;
            Node t = start;
            while (s != end) {
                t = s;
                s = s.getLink();
            }
            end = t;
            end.setLink(null);
            size--;
            return;
        }
        Node ptr = start;
        pos = pos - 1;
        for (int i = 1; i < size - 1; i++) {
            if (i == pos) {
                Node tmp = ptr.getLink();
                tmp = tmp.getLink();
                ptr.setLink(tmp);
                break;
            }
            ptr = ptr.getLink();
        }
        size--;
    }

    public void display() {
        System.out.print("\nSingly Linked List = ");
        if (size == 0) {
            System.out.print("empty\n");
            return;
        }
        if (start.getLink() == null) {
            System.out.println(start.getData());
            return;
        }
        Node ptr = start;
        System.out.print(start.getData() + "->");
        ptr = start.getLink();
        while (ptr.getLink() != null) {
            System.out.print(ptr.getData() + "->");
            ptr = ptr.getLink();

        }

        System.out.print(ptr.getData() + "\n");

    }

    // This method will make the linked list in ascending order
    void ascending() {
        Node ptr = start, next = null;
        int tempData;   // to store temp data during operation

        // if list is not empty
        if (!isEmpty()) {
            // keep looping until ptr becomes null,
            // means until whole list is iterated
            while (ptr != null) {
                // next link
                next = ptr.getLink();

                // keep looping until next ptr becomes null
                while (next != null) {
                    // if current node data is greater than next, swap the nodes
                    if (ptr.getData() > next.getData()) {
                        tempData = ptr.getData();
                        ptr.setData(next.getData());
                        next.setData(tempData);
                    }
                    // move next to next position
                    next = next.getLink();
                }
                ptr = ptr.getLink();
            }
        }
    }

}


/* Class SinglyLinkedList */
public class SinglyLinkedList {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        /* Creating object of class linkedList */
        linkedList list = new linkedList();

        System.out.println("Singly Linked List Test\n");

        char ch;

        /* Perform list operations */
        do {
            System.out.println("\nSingly Linked List Operations\n");
            System.out.println("1. insert at begining");
            System.out.println("2. insert at end");
            System.out.println("3. insert at position");
            System.out.println("4. delete at position");
            System.out.println("5. check empty");
            System.out.println("6. get size");
            System.out.println("7. linked list in ascending order");

            int choice = scan.nextInt();

            switch (choice) {
                case 1:
                    System.out.println("Enter integer element to insert");
                    list.insertAtStart(scan.nextInt());
                    break;
                case 2:
                    System.out.println("Enter integer element to insert");
                    list.insertAtEnd(scan.nextInt());
                    break;
                case 3:
                    System.out.println("Enter integer element to insert");
                    int num = scan.nextInt();
                    System.out.println("Enter position");
                    int pos = scan.nextInt();
                    if (pos <= 1 || pos > list.getSize()) {
                        System.out.println("Invalid position\n");
                    } else {
                        list.insertAtPos(num, pos);
                    }
                    break;
                case 4:
                    System.out.println("Enter position");
                    int p = scan.nextInt();
                    if (p < 1 || p > list.getSize()) {
                        System.out.println("Invalid position\n");
                    } else {
                        list.deleteAtPos(p);
                    }
                    break;
                case 5:
                    System.out.println("Empty status = " + list.isEmpty());
                    break;
                case 6:
                    System.out.println("Size = " + list.getSize() + " \n");
                    break;
                case 7:
                    list.ascending();
                    break;

                default:
                    System.out.println("Wrong Entry \n ");
                    break;
            }

            /* Display List */
            list.display();

            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);

        } while (ch == 'Y' || ch == 'y');
    }
}

Below is the sample output:

This completes the requirement. Let me know if you have any questions.

Thanks!


Related Solutions

Leave code as is ALL I NEED IS TO MAKE THE LIST INTO ASCENDING ORDER FROM...
Leave code as is ALL I NEED IS TO MAKE THE LIST INTO ASCENDING ORDER FROM A TO Z OF ARTISTS NAMES YOU CAN USE THIS AS REFERENCE SPOTIFY LIST TOP 50 AS REFERENCE FOR CSV FILE https://spotifycharts.com/viral/ import java.io.*; public class Spotify { public static void main(String[]args) { // Read csv Spotify file located on my desktop // Download csv file, save on desktop, and add file location in csvFile = " " String csvFile = "CSVFILE LOCATION OF...
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added....
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added. (DO NOT MODIFY THE HEADER FILE OR TEST FILE. only modify the list.cpp) /*LIST.CPP : */ #include "list.h" using namespace std; // Node class implemenation template <typename T> Node<T>::Node(T element) { // Constructor    data = element;    previous = nullptr;    next = nullptr; } // List implementation template <typename T> List<T>::List() {    head = nullptr;    tail = nullptr; } template...
PLEASE INCLUDE THE SOURCE CODE AND OUTPUT PLEASE AND THANKS!!This assignment covers recursion and linked list...
PLEASE INCLUDE THE SOURCE CODE AND OUTPUT PLEASE AND THANKS!!This assignment covers recursion and linked list which include the following tasks: 2. a. Using C/C++, construct a single linked list of 8 nodes and assign random numbers as the nodes’ values. Then print the list from the first node to the last. Finally, free all memories of the linked list. b. Using C/C++, construct a single linked list of 8 nodes and assign random numbers as the nodes’ values. Then...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment? x.next = x.next.next b. Singly Linked List has two private instance variables first and last as that point to the first and the last nodes in the list, respectively. Write a fragment of code that removes the last node in a linked list whose first node is first....
Linked List: Complete the following code to create a linked list from an Array. After creating...
Linked List: Complete the following code to create a linked list from an Array. After creating the list, display the elements of the linked list iteratively. Write two others function called as RDisplayTailRecursion(first) and RDisplayTailRecursion(first) which will print elements of the linked list using the tail and head recursions respectively. #include <stdio.h> #include <stdlib.h> struct Node { }*first=NULL; void create(int A[], int n) { for(i=1; i<n; i++) { } } void Display(struct Node*p) { while(p!=NULL) { } } void RDisplayTailRecursion...
PLEASE SOLVE THIS QUESTION WITHOUT CHANGING THE SOURCE CODE POSTED BELOW. (ONLY ADDING) #include <iostream> using...
PLEASE SOLVE THIS QUESTION WITHOUT CHANGING THE SOURCE CODE POSTED BELOW. (ONLY ADDING) #include <iostream> using namespace std; const int arrSize = 3; // QUESTION ii. COMPLETE A displayMatrix(...) FUNCTION HERE // QUESTION iii. COMPLETE A transposedMatrix(...) FUNCTION HERE // QUESTION iv. COMPLETE A calculateTotal(...) FUNCTION HERE int main(){ // variable declaration int mat[arrSize][arrSize], transMat[arrSize][arrSize] = {0}, total = 0; // QUESTION i. Prompt user to enter 9 integer numbers and fill in into the matrix cout << "\nThe original...
how do you add two matrices linked list in java? (am using linked list because 2D...
how do you add two matrices linked list in java? (am using linked list because 2D arrays are not allowed.) ex [1st matrix] 1 3 2 4 2 1 3 2 4 + [2nd matrix] 3 2 3 2 1 4 5 2 3 = [3rd matrix] 4 5 5 6 3 5 8 4 7
list in ascending order the levels of hierarchy of complexity. define each level and provide an...
list in ascending order the levels of hierarchy of complexity. define each level and provide an example for each.
***C++ Coding*** Write a program for sorting a list of integers in ascending order using the...
***C++ Coding*** Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. Please include comments to understand code. Requirements Implement the following functions: int readData( int **arr) arr is a pointer to pointer for storing the integers. The function returns the number of integers. The function readData reads the list of integers from a file call data.txt into the array arr. The first integer number in the file is the number of intergers....
C++ Write a program for sorting a list of integers in ascending order using the bubble...
C++ Write a program for sorting a list of integers in ascending order using the bubble sort algorithm Requirements Implement the following functions: Implement a function called readData int readData( int **arr) arr is a pointer for storing the integers. The function returns the number of integers. The function readData reads the list of integers from a file call data.txt into the array arr. The first integer number in the file is the number of intergers. After the first number,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT