Question: I need help with my program. I get it to switch the first two words but it doesnt loop through again. Below is the code

I need help with my program. I get it to switch the first two words but it doesnt loop through again. Below is the code i have so far
import java.util.Scanner;
class Node
{
public String data;
public Node next;
//default constructor
public Node()
{
}
public Node getNode(int i) {
// TODO Auto-generated method stub
return null;
}
public String getData()
{
return data;
}
public void setData(String s)
{
s = data;
}
}
class LinkedList
{
private Node head;
//default constructor
public LinkedList()
{
}
/*
* adds to the head of linked list
* @param String data
* @returns void
*/
public void addHead(String data)
{
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
}
/*
* adds to the tail of linked list
* @param String data
* @returns void
*/
public void addTail(String data)
{
Node current = head;
if(current == null)
{
addHead(data);
}
else
{
while(current.next != null)
{
current = current.next;
}
Node newNode = new Node();
newNode.data = data;
current.next = newNode;
}
}
public int size()
{
int x =0;
Node Curr = head;
while(Curr.next != null)
{
Curr = Curr.next;
x++;
}
return x;
}
public Node getNode(int x)
{
Node curr = head;
int count =0;
while(curr != null)
{
if(count == x)
{
return curr;
}
count++;
curr=curr.next;
}
return null;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
String result = "";
Node current = head;
while(current!=null)
{
result += current.getData() + " ";
current = current.next;
}
return result;
}
public Node getHead()
{
return head;
}
public void insertionSort()
{
Node current = head;
Node temp= new Node();
Node temp1= new Node();
for(int i = 0; i { while(current.next!=null && current.next.getData().compareTo(current.getData()) { if(current==head) { temp=current; temp1=current.next.next; head=current.next; head.next = temp; head.next.next =temp1; } else { temp=current; temp1=current.next.next; current=current.next; current.next =temp; current.next.next=temp1; } current=current.next; } } } } //main class public class InsertionSort { public static void main(String[] args) { LinkedList ll = new LinkedList(); System.out.println("Displaying Singly Linked List Contents not sorted: "); String example = "what if cat really spelled meant dog"; //separating string into individual words Scanner s = new Scanner(example).useDelimiter("\\s"); while( s.hasNext() ) { ll.addTail(s.next());//adding words to tail of linkedlist } s.close(); //printing list System.out.println(ll.toString()); ll.insertionSort(); System.out.println(ll.toString()); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
