i have been given an assignment to create a singly linked list which maintains order. but i am not sure whether to use a sorting method or to take care of the sorting while adding the values in the list. i guess i am correct to decide the second option because if we insert values according to the order, then the list is automatically a sorted one.
my code for now is as below:
Link.java
LinkList.java
Kindly, advice me what is the best thing for me to do. If i am rite with my move then i need to know how to do the insert operation. how do we loop through each node of a linked list and what is the algorithm for me to follow.
i can think about iterating through each node and comparing the value in the node with the value i am about to add, if(currentnode. next.element > value && currentnode.ele ment < value) then i can create a node in between those nodes and insert the new element. but i am not sure how to implement my idea in code.
any suggestions would be appreciated.
my code for now is as below:
Link.java
Code:
package LinkedList;
public class Link {
public String data;
public Link next;
public Link(){
this.next = null;
}
public Link(String data){
this.data = data;
}
public void display(){
System.out.println(data);
}
public String toString(){
return data;
}
public static void main(String[] args) {
LinkList theLinkedList = new LinkList();
int size = theLinkedList.size();
System.out.println("Size of the Linked List: "+size);
System.out.println("The value stored in Linked List initially is: "+theLinkedList.firstLink);
theLinkedList.insertFirstLink("X");
System.out.println("Value of head node in Linked List after adding: " + theLinkedList.firstLink);
theLinkedList.removeFirst();
System.out.println("The value stored in Linked List after deletion: "+theLinkedList.firstLink);
}
}
Code:
package ucsc;
class LinkList{
public Link firstLink;
LinkList(){
firstLink = null;
}
public int size(){
Link temp = new Link();
int counter = 0;
while(temp!=null){
temp = temp.next;
counter++;
}
return counter;
}
public boolean isEmpty(){
return(firstLink == null);
}
public void insertFirstLink(String data){
Link newLink = new Link(data);
newLink.next = firstLink;
firstLink = newLink;
}
public Link removeFirst(){
if(!isEmpty()){
firstLink = firstLink.next;
} else {
System.out.println("Empty LinkedList");
}
return firstLink;
}
public void display(){
Link theLink = firstLink;
while(theLink != null){
System.out.println(theLink);
theLink = theLink.next;
System.out.println();
}
}
}
i can think about iterating through each node and comparing the value in the node with the value i am about to add, if(currentnode. next.element > value && currentnode.ele ment < value) then i can create a node in between those nodes and insert the new element. but i am not sure how to implement my idea in code.
any suggestions would be appreciated.
Comment