my code for now is as below:
Link.java
Expand|Select|Wrap|Line Numbers
- 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);
- }
- }
Expand|Select|Wrap|Line Numbers
- 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.element < 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.