Hello. I am an international student trying to solve my assignment which requires to implement Circular Linked List. I asked my lecturer to check my work and she said that I solved it but actually still using the normal Linked List (Linear). She hinted me that I need to modify my program to get the Circular Linked List.
So I'm still confused. In theory, I do know the difference between Linked List & Circular Linked List. However, since I've only learnt Linked List so far so I thought that playing some tricks on Linked List would do create the Circular.
But seems that I was wrong. So I am confused! I mean, is there a new code or way or something to make it Circular Linked List?
Help me.
I give you three classes consist of ListNode, CLL and the Main class.
Expect for your reply A.S.A.P since I need to submit it in next week.
Many thanks in advance!
This is ListNode class
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
This is CLL class
public class CLL {
private ListNode head;
public CLL() {
head = null;
}
//Add node of data to Linked List
public void addToList(int data){ //Using addToTail method
ListNode current = head; //Set head as current
ListNode newNode = new ListNode(data); //Create a new node with data in it
if (head == null) { //If head is empty then
head = newNode; //newNode (that has data) set to head
}
else { //If head is already filled then
while (current.getNext() != null) { //If the next node is filled
current = current.getNext(); //Move on the next node
}
current.setNext(newNode); //Until next node is null, create new node at the end (tail).
}
}
public int LuckySuitor(int count){
ListNode current = head, previous = null;
int toDel,s, LuckyGuy;
count--;
for(s=1; s<=count; s++){
for (toDel=1; toDel<=2; toDel++){
if (current.getNext() == null){
previous = current;
current = head;
}// End if
else{
previous = current;
current = current.getNext();
}// End else
}// End for
if (current.getNext() == null)
current = head;
else
current = current.getNext();
previous.setNext(current);
}
LuckyGuy = current.getData();
return LuckyGuy;
}// End LuckySuitor
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.getData() + "<-");
current = current.getNext();
}
System.out.println("null");
}
}
This is Main Class
import java.util.Scanner;
public class CLL_Main {
public static void main(String[] args) {
CLL Suitors = new CLL();
int s;
Scanner input = new Scanner (System.in);
int n;
System.out.println("Enter the number of suitors: ");
n = input.nextInt();
for (s=1; s <= n; s++)
Suitors.addToList(s);
Suitors.printList();
System.out.println("The lucky guy is: " + Suitors.LuckySuitor(n));
}
}