Circular Linked List In Ascending Order Java - java

My task is to implement a circular linked list in java (ascending order) but the problem is that it is going in an infinite loop
I have created a class of Node in which i have define two elements.
public class Node {
public int element;
public Node next;
public class Node {
int element;
Node next;
}
}
Now in the second class of List i have made a insert function i have define a Node head=null in the start and create a new nNode .After that i am checking in the head section if head==null then the first element will be nNode. After inserting the first element i will compare the next element and the head element if the head element is greater than it will shift next and the new nNode will be the head. Since it is the circular linked list it is working but it is also going in an infinite loop.
This is the List class in which i have use the node class variables
public class List {
void insert(int e) {
Node nNode = new Node();
Node tNode = head;
nNode.element = e;
if (head == null)
head = nNode;
else if (head.element > e) {
nNode.next = head;
head=nNode;
} else {
Node pNode = head;
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
pNode.next = nNode;
nNode.next = tNode;
tNode.next=head;
}
}
}

I have created on sample program for circular linkedlist which hold name and age of given element.
It has add(), remove() and sorbasedOnAge() (Sorting is implemented by first getting clone and convert it into simple linked list. Then use merge sort so that performance of O(nLogn) could be achieved.)
If you like it don't forget to press like button.
package com.ash.practice.tricky;
import java.util.Collections;
import java.util.LinkedList;
public class CircularLinkedList implements Cloneable{
Node start;
public Node getHead() {
return start;
}
CircularLinkedList setHead(Node startNode) {
start = startNode;
return this;
}
public void add(String name, int age) {
if(name==null) {
System.out.println("name must not be null.");
return;
}
if(start == null) {
Node node = new Node(name,age);
start = node;
node.next = start;
} else {
Node node = new Node(name,age);
Node temp = start;
while(temp.next != start) {
temp = temp.next;
}
temp.next = node;
node.next = start;
}
}
public CircularLinkedList clone()throws CloneNotSupportedException{
return (CircularLinkedList)super.clone();
}
public boolean remove(String name) {
if(name==null) {
return false;
} else if(start==null) {
return false;
} else if(start.getName().equals(name)) {
if(size()>1) {
Node temp = start;
while(temp.next!=start) {
temp = temp.next;
}
temp.next = start.next;
start = start.next;
} else {
start = null;
}
return true;
} else {
Node temp = start;
Node next = null;
Node prev = null;
while(temp.next != start) {
String currName = temp.name;
if(currName.equals(name)) {
next = temp.next;
break;
} else {
temp = temp.next;
}
}
if(next == null) {
return false;
}
prev = temp.next;
while(prev.next!=temp) {
prev = prev.next;
}
prev.next = next;
temp = null;
return true;
}
}
/*
public Node getPrevious(String name, int age) {
Node curr = new Node(name,age);
Node temp = curr;
while(temp.next!=curr) {
temp = temp.next;
}
return temp;
}
*/
public int size() {
int count = 1;
if(start != null) {
Node temp = start;
while(temp.next!=start) {
count++;
temp = temp.next;
}
} else return 0;
return count;
}
public int listSize() {
int count = 1;
if(start != null) {
Node temp = start;
while(temp.next!=null) {
count++;
temp = temp.next;
}
} else return 0;
return count;
}
public void display() {
if(start == null) {
System.out.println("No element present in list.");
} else {
Node temp = start;
while(temp.next != start) {
System.out.println(temp);
temp = temp.next;
}
System.out.println(temp);
}
}
public void displayList() {
if(start == null) {
System.out.println("No element present in list.");
} else {
Node temp = start;
while(temp.next != null) {
System.out.println(temp);
temp = temp.next;
}
System.out.println(temp);
}
}
public Node getPrevious(Node curr) {
if(curr==null) {
return null;
} else {
Node temp = curr;
while(temp.next!=curr) {
temp = temp.next;
}
return temp;
}
}
Node getMiddle() {
Node result = null;
Node temp = start.next;
result = start.next;
Node end = getPrevious(start);
end.next = null;
while(temp.next!=null) {
if(temp.next.next!=null) {
temp = temp.next.next;
result = result.next;
} else {
return result;
}
}
return result;
}
private static CircularLinkedList SortCollections(CircularLinkedList list) {
return SortCollections.doSortBasedOnAge(list);
}
private static class Node {
Node next;
String name;
int age;
Node(String name,int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
public String toString() {
return "name = "+name +" : age = "+age;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
private static class SortCollections {
static Node mergeSort(Node head) {
if(head == null || head.next == null) {
return head;
}
Node middle = getMiddle(head);
Node nextHead = middle.next;
middle.next = null;
Node left = mergeSort(head);
Node right = mergeSort(nextHead);
Node sortedList = sortedMerged(left, right);
return sortedList;
}
public static CircularLinkedList doSortBasedOnAge(CircularLinkedList list) {
CircularLinkedList copy = null;
try {
copy = list.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
if(copy!=null) {
Node head = copy.getHead();
Node end = copy.getPrevious(head);
end.next = null;
Node startNode = mergeSort(head);
CircularLinkedList resultList = new CircularLinkedList().setHead(startNode);
return resultList;
} else {
System.out.println("copy is null");
}
return null;
}
private static Node sortedMerged(Node a, Node b) {
if(a == null) {
return b;
} else if(b == null) {
return a;
}
Node result = null;
if(a.getAge() > b.getAge()) {
result = b;
result.next = sortedMerged(a, b.next);
} else {
result = a;
result.next = sortedMerged(a.next, b);
}
return result;
}
private static Node getMiddle(Node head) {
Node result = null;
Node temp = head;
result = head;
while(temp.next!=null) {
if(temp.next.next!=null) {
temp = temp.next.next;
result = result.next;
} else {
return result;
}
}
return result;
}
}
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
Collections.sort(new LinkedList());
list.add("ashish", 90);
list.add("rahul", 80);
list.add("deepak", 57);
list.add("ankit", 24);
list.add("raju", 45);
list.add("piyush", 78);
list.add("amit", 12);
//list.display();
/*System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("deepak"));
//list.display();
System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("ashish"));
//list.display();
System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("raju"));
//list.display();
System.out.println("---------------- size = "+list.size());
list.add("aman", 23);
System.out.println("---------------- size = "+list.size());
list.display();
System.out.println("Previous Node of second node is : "+list.getPrevious(list.start.next));
System.out.println("Previous Node of start node is : "+list.getPrevious(list.start));
System.out.println("Previous Node of piyush node is : "+list.getPrevious("piyush",78));*/
list.display();
System.out.println("---------------- size = "+list.size());
//System.out.println(list.getMiddle());
CircularLinkedList newList = CircularLinkedList.SortCollections(list);
newList.displayList();
System.out.println("---------------- size = "+newList.listSize());
}
}

Let's consider the following situation:
The list contains elements B,C,X. Now you want to insert A and then Z.
void insert(int e) {
Node nNode = new Node(); //the new node, step 1: A, step2: Z
Node tNode = head; //step1: points to B, step2: points to A
nNode.element = e;
if (head == null) { //false in both steps
head = nNode;
head.next = head; //I added this line, otherwise you'd never get a circular list
} //don't forget the curly braces when adding more than one statement to a block
else if (head.element > e) { //true in step 1, false in step 2
nNode.next = head; //A.next = A
head=nNode; //A is the new head, but X.next will still be B
} else {
//you'll enter here when adding Z
Node pNode = head; //points to A because of step 1
//when tNode = X you'll start over at B, due to error in step 1
//the condition will never be false, since no node's next will point to A
//and no node's element is greater than Z
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
//in contrast to my previous answer, where I had an error in my thought process,
//this is correct: the node is inserted between pNode and tNode
pNode.next = nNode;
nNode.next = tNode;
tNode.next=head; //delete this
}
}
As you can see, there are at least the following problems in your code:
tNode.next=head; is not necessary, since if you insert a node between pNode and tNode, tNode.next should not be affected (and if tNode is the last node, next should already point to the head, while in all other cases this assignment would be wrong).
In the two branches above, where you set head, you're not setting the next element of the last node to head. If you don't do this when adding the first node, that's not necessarily a problem, but leaving that out when adding a new head (second condition) you'll produce an incorrect state which then might result in endless loops
What you might want to do:
Remove the tNode.next=head; statement.
If you add a new head locate the last node and set the head as its next node. That means that if you have only one node, it references itself. If you add a node at the front (your second condition) you'll have to update the next reference of the last node, otherwise you'll get an endless loop if you try to add an element at the end.

After working two days on the code I finally solved it but this is not efficient code .
void insert(int e) {
Node nNode = new Node(); //the new node, step 1: A, step2: Z
Node tNode = head; //step1: points to B, step2: points to A
nNode.element = e;
if (head == null) { //false in both steps
head = nNode;
head.next = head;
}
else if (head.element > e) { //true in step 1, false in step 2
Node pNode = head;
pNode=tNode.next; //PNode is at head which will equal to tNode.next Which will be the next element
nNode.next = head;
head=nNode;
tNode.next.next=nNode; // Now I am moving the Tail Node next
} else {
Node pNode=head; //points to A because of step 1
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
pNode.next = nNode;
nNode.next = tNode;
}
}

Related

Re-order single linked list if elements have been searched?

public class SearchLinkedList<E> {
private Node<E> first;
public static void main(String[] args){
SearchLinkedList<Integer> list = new SearchLinkedList<Integer>();
list.insert(1000);
list.insert(2000);
list.insert(3000);
System.out.println(list.getFirst());
}
public SearchLinkedList() {
first = null;
}
public void insert(E e) {
if (first == null) {
first = new Node<E>(e);
} else {
//while(temp.next.searched == true) then insert new Node where the next node is null or searched == false
Node<E> temp = new Node<E>(e);
temp.next = first;
first = temp;
}
}
public E getFirst() {
return first.data;
}
public E find(E x) {
if (first == null) {
return null;
} else {
//while (temp != null) if node found set it's searched = true and move it to front of list
Node<E> temp = first;
while (temp != null) {
if (temp.data.equals(x)) {
temp.searched = true;
return temp.data;
}
temp = temp.next;
}
return temp.data;
}
}
private static class Node<E> {
private E data;
private boolean searched;
private Node<E> next;
private Node(E e) {
data = e;
searched = false;
next = null;
}
}
}
So the assignment here is to create a LinkedList class that moves a node to the front of the list (first) if it has been searched.
First image here is when this is called:
list.insert(1000);
list.insert(2000);
list.insert(3000);
Second image is when this is called:
list.find(3000);
list.find(2000);
So the goal is when find is called and node with data is found: Set it's searched boolean to true and move that node to front of list. As of now, my insert just puts new node at the front of list. The comments in insert and find explain what I want to make them do. However, moving an element from the middle of a single linkedlist to front seems hard. Don't know what to do here. You can copy and try this yourself. After calling list.find(2000); and then list.getFirst() We should get 2000. Question is how... My thoughts are on if I should let the Node's booleans decide whether to be infront or not... Not sure here at all.
Thanks to danilllo19 for the help. That answer is correct only issue was that the new elements should be added from the front and so if an element is searched we're supposed to add the new one after the last searched but at the head of the un-serached ones. Solved it like this:
public void insert(E e) {
if(first == null){
first = new Node<E>(e);
}else{
Node<E> temp = first;
while(temp.searched && temp.next != null && temp.next.searched){
temp = temp.next;
}
Node<E> node = new Node<E>(e);
if(temp.searched && temp.next != null && !temp.next.searched){
Node<E> temp2 = temp.next;
temp.next = node;
node.next = temp2;
}else if(temp.searched && temp.next == null){
temp.next = node;
}else{
node.next = temp;
first = node;
}
}
}
I suppose you should do it like this:
public class SearchLinkedList<E> {
private Node<E> first;
public static void main(String[] args) {
SearchLinkedList<Integer> list = new SearchLinkedList<Integer>();
list.insert(1000);
list.insert(2000);
list.insert(3000);
System.out.println(list.getFirst());
System.out.println(list.find(3000));
System.out.println(list.getFirst());
list.insert(4000);
System.out.println(list.find(200));
}
public SearchLinkedList() {
first = null;
}
public void insert(E e) {
if (first == null) {
first = new Node<E>(e);
} else {
//while(temp.next.searched == true) then insert new Node where the next node is null or searched == false
Node<E> temp = first;
while (temp.next != null && temp.next.searched) {
temp = temp.next;
}
Node<E> node = new Node<>(e);
if (temp.next != null) {
node.next = temp.next;
}
temp.next = node;
}
}
public E getFirst() {
return first.data;
}
public E find(E x) {
if (first == null) {
return null;
} else {
//while (temp != null) if node found set it's searched = true and move it to front of list
Node<E> temp = first;
while (temp != null) {
if (temp.data.equals(x)) {
temp.searched = true;
break;
}
temp = temp.next;
}
if (temp == null) return null;
pushForward(temp);
return temp.data;
}
}
//Find pre-linked node with our node, bind our node with parent next node
//and link parent with node.
private void pushForward(Node<E> node) {
if (first == null || first.next == null) return;
Node<E> temp = first;
while (temp.next != null) {
if (temp.next.equals(node)) {
temp.next = temp.next.next;
node.next = first;
first = node;
break;
}
temp = temp.next;
}
}
private static class Node<E> {
private E data;
private boolean searched;
private Node<E> next;
private Node(E e) {
data = e;
searched = false;
next = null;
}
}
}
Also you could mix pushForward and find methods to make find to do what you want by one iteration through the list (O(n)), because O(n^2) there.
Might be helpful: https://www.geeksforgeeks.org/java-program-for-inserting-node-in-the-middle-of-the-linked-list/

JAVA- Printing out LinkedLists in an ArrayList [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 1 year ago.
I am trying to print out the elements in my ArrayList that looks like
static ArrayList<LinkedList> listy = new ArrayList<>();
I tried to create a function called PrintTest()
public static void pTest() {
String [] top;
for (LinkedList i: listy) {
//i.show();
System.out.println(i.toString());
However, I am still getting when I call printTest()
LinkedList#15975490
LinkedList#6b143ee9
LinkedList#1936f0f5
LinkedList#6615435c
LinkedList#4909b8da
LinkedList#3a03464
LinkedList#2d3fcdbd
LinkedList#617c74e5
Do I need to iterator over this once more? I am confused on how to go about this. Can I override toString()? I can't seem to get it to work
Here is my linkedlist implementation code
public class LinkedList {
Node head;
Node tail;
public String getFirst() {
Node node = head;
if (node.next == null) {
throw new NoSuchElementException();
}
else {
return node.data;
}
}
public void insert(String data) {
Node node = new Node();
node.data = data;
node.next = null;
if (head == null) {
head = node;
}
else {
Node n = head;
while(n.next !=null) {
n = n.next;
}
n.next = node;
}
}
public void insertAtStart(String data) {
Node node = new Node();
node.data = data;
node.next = null;
node.next = head;
head = node;
}
public void insertAt(int index, String data) {
Node node = new Node();
node.data = data;
node.next = null;
if(index == 0) {
insertAtStart(data);
}
else {
Node n = head;
for (int i = 0; i < index-1; i++) {
n = n.next;
}
node.next = n.next;
n.next = node;
}
}
public void deleteAt(int index) {
if (index == 0) {
head = head.next;
}
else {
Node n = head;
Node n1 = null;
for (int i = 0; i < index-1; i++) {
n = n.next;
}
n1 = n.next;
n.next = n1.next;
//System.out.println("n1 " + n1.data);
n1 = null;
}
}
public int size() {
int count =0;
Node pos = head;
while (pos != null) {
count++;
pos = pos.next;
}
return count;
}
public void remove(String s) {
Node node = head;
while (!node.data.equals(s)) {
node = node.next;
}
if (node.next == null) {
node.data = null;
}
else {
node.data = node.next.data;
node.next = node.next.next;
}
//System.out.println("n1 " + n1.data);
}
public void show() {
Node node = head;
while(node.next != null) {
System.out.println(node.data);
node = node.next;
}
System.out.println(node.data);
In java, every class inherits the Object class. In the Object class default definition for the toString method is hashcode. When you are calling toString method, you need to define by yourself.
class LinkedList{
int value;
#Override
public String toString(){
return String.valueOf(value);
}
}
I think you can go through this article to get more understanding.Explanation For toString

Deleting a specific node in a singly linked list(java)

So my problem is that I wanna delete a node based on a value inputted by the user, in my program I can already, add, search, and delete the node in the last position, but so far I haven't been able to delete a specific value inputted by the user, if for example I have 1,2,3,4 elements in my list I wanna be able to point at, say 2, and delete it. here are my functions, the last one is the uncompleted one:
//searches node
public void searchNode(int input){
Node temp = first;
boolean found = false;
if(!isEmpty()){
for(int i = 0 ; i<size ; i ++){
if(temp.value == input){
System.out.println(input + " found in the position: " + (i+1));
found = true;
break;
}
temp = temp.rightNode;
}
if(!found)
System.out.println("value not found.");
}
}
//deletes last node
public void deleteLastNode(){
if(isEmpty()){
System.out.println("There are no nodes to delete.");
}
if(last == first){
first = null;
last = null;
} else {
Node current = first;
while(current.rightNode != last){
current = current.rightNode;
}
current.rightNode = null;
last = current;
}
size --;
}
//delete element, input by user.
public void deleteInputByUser(int input) {
Node temp = first;
boolean found = false;
if(isEmpty()){
System.out.println("There are no nodes to delete.");
} else {
}
size--;
}
//Node class
public class Node{
int value;
Node rigthNode;
public Node(int value){
this.value = value;
}
}
Deletion of a node in a Linked List by value is not so bad. This pseudocode should help you get started:
deleteNodeByValue(int val) {
if (head.val = val) {
head = head.next
return
}
current = head
while (current.next != null) {
if (current.next.val = val) {
current.next = current.next.next
return
}
current = current.next
}
}
Find the nodeToDelete and his previousNode, then
previousNode.rightNode = nodeToDelete.rightNode;
you can do it this way. The following code will remove the element once the index is given.
public boolean deleteAt(int index){
Node current=first;
if(index==0){
first=current.rightNode;
return true;
}
currentIndex=0;
previousNode=first;
current=first.rightNode;
while(current!=null){
if(currentIndex==index){
previousNode.rightNode=current.rightNode;
return true;
}
currentIndex++;
previousNode=current;
current=current.rightNode;
}
return false;
}
You could try something like that.
public void deleteNodeByValue(int input) {
Node currNode = first;
boolean found = false;
Node prevNode = first;
if (!isEmpty()) {
for (int i = 0; i < size; i++) {
if (currNode.value == input) {
///////DELETE START
if (currNode == first) {
first = currNode.rightNode;
} else {
prevNode.rightNode = currNode.rightNode;
if (currNode == last)
last = prevNode;
}
////DELETE END
found = true;
size--;
break;
}
prevNode = currNode;
currNode = currNode.rightNode;
}
if (!found)
System.out.println("value not found.");
}
}

Rotate a singly linked list in Java

My functions:
import java.util.Collection;
import java.util.Collections;
public class LinkedList {
private Node head;
private int listCount;
// konstruktor na povrzanata lista
public LinkedList()
{
// ova e prazna lista, pa zatoa 'head' pokazuva kon nov jazok bez elementi (null)
head = new Node(null);
listCount = 0;
}
// dodavame element (data) na krajot od listata
public void add(Object data)
{
Node temp = new Node(data);
Node current = head;
head.setData(temp.getData());
// pocnuvajki od 'head' (pocetniot element) pominuvame niz site lemenenti
while(current.getNext() != null)
{
current = current.getNext();
}
current.setNext(temp);
// go zgolemuvame brojot na elementi vo listata
listCount++;
}
// dodavame element (data) na posebno opredelena pozicija (index)
public void add(Object data, int index)
{
Node temp = new Node(data);
Node current = head;
head.setData(temp.getData());
// odime do baraniot index, ili do posledniot element od listata (do koj stigneme prvo)
for (int i = 1; i < index && current.getNext() != null; i++)
{
current = current.getNext();
}
// go postavuvame sledniot element na novata jazla
// da pokazuva kon sledniot element na ovaa jazla
temp.setNext(current.getNext());
// a sega go postavuvame sledniot element na ovaa jazla
// da pokazuva kon novata jazla
current.setNext(temp);
// go nakacuvame vkupniot broj na elementi vo listata
listCount++;
}
// vraka element na opredelena pozicija vo listata
public Object get(int index)
{
if(index <= 0)
{
return null;
}
Node current = head.getNext();
for(int i = 1; i < index; i++)
{
if(current.getNext() == null)
{
return null;
}
current = current.getNext();
}
return current.getData();
}
// go vrakame brojot na elementi vo listata
public int size()
{
return listCount;
}
// go brisime elementot na opredelenata pozicija vo listata
public boolean remove(int index)
{
if(index < 1 || index > size())
{
return false;
}
Node current = head;
for(int i = 1; i < index; i++)
{
if(current.getNext() == null)
{
return false;
}
current = current.getNext();
}
current.setNext(current.getNext().getNext());
// go namaluvame brojot na elementi vo listata
listCount--;
return true;
}
public boolean contains(Object data)
{
Node temp = new Node(data);
Node current = head;
for(int i = 0; i < size(); i++)
{
if(temp.getData().equals(current.getData()))
{
return true;
}
else
{
current = current.getNext();
}
}
return false;
}
public Node inserAfter(Object data, Node n)
{
Node temp = new Node(data);
Node current = n.getNext();
temp.setNext(current);
n.setNext(temp);
return temp;
}
public void rotateLeft()
{
Node temp = head;
//head = head.getNext();
//Node tail = head.getNext();
if (head != null) { //otherwise it is empty list
//Node temp = head;
if (head.getNext() != null) { //otherwise it is single item list
head = head.getNext();
}
}
Node tail;
if (head.getNext() != null) {
//more than 2 items in the list
tail = head.getNext();
} else {
//only 2 items in the list
tail = head;
}
while(tail.getNext() != null)
{
if (tail.getNext() != null) {
tail = tail.getNext();
}
//tail = tail.getNext();
}
tail.setNext(temp);
temp.setNext(null);
}
public void rotateRight()
{
Node temp = null;
Node current = head;
while(current.getNext() != null)
{
temp = current;
current = current.getNext();
}
current.setNext(head);
head = current;
temp.setNext(null);
}
public void reverse()
{
Node reversedPart = null;
Node current = head;
while(current != null)
{
Node next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;
}
public Node copyList(Node source)
{
Node copyHead = null;
Node copyTail = null;
Node temp = new Node(source);
Node current = head.getNext();
for(int i = 0; i < size(); i++)
{
Node newNode = new Node(temp.getData());
if(copyHead == null)
{
copyHead = newNode;
copyTail = copyHead;
}
else
{
copyTail.setNext(newNode);
copyTail = copyTail.getNext();
}
}
return copyHead;
}
public Object setDataIndexOf(Object data, int index)
{
Node node = nodeAt(index);
if(node == null)
{
return null;
}
else
{
Object old = node.getData();
node.setData(data);
return old;
}
}
public Object dataAt(int index)
{
Node current = head.getNext();
if(index < 1 || index > size())
{
return null;
}
for(int i = 0; i < index; i ++)
{
if(i != index - 1)
{
current = current.getNext();
}
}
return current.getData();
}
public Node nodeAt(int index)
{
Node current = head.getNext();
if(index < 1 || index > size())
{
return null;
}
for(int i = 0; i < index; i++)
{
if(i != index - 1)
{
current = current.getNext();
}
}
return current;
}
public int indexOf(Object data)
{
Node temp = new Node(data);
Node current = head.getNext();
for(int i = 0; i < size(); i++)
{
if(current.getData().equals(temp.getData()))
{
return i;
}
current = current.getNext();
}
return -1;
}
public Object min()
{
Integer min = (Integer)head.getData();
Node current = head;
while(current.getNext() != null)
{
if((Integer)current.getData() < min)
{
min = (Integer)current.getData();
}
current = current.getNext();
}
return min;
}
public Object max()
{
Integer max = (Integer)head.getData();
Node current = head;
while(current.getNext() != null)
{
if((Integer)current.getData() > max)
{
max = (Integer)current.getData();
}
current = current.getNext();
}
return max;
}
public void removeSecondAppear(Object data)
{
Node temp = new Node(data);
Node current = head;
Node previous = null;
boolean found = false;
while(current != null)
{
if(current.getData().equals(temp.getData()) && current.getData() != null)
{
if(found == true)
{
previous.setNext(current.getNext());
break;
}
else if(found == false)
{
found = true;
}
}
else{
found = false;
}
previous = current;
current = current.getNext();
}
}
public String toString()
{
Node current = head.getNext();
String output = "";
while(current != null)
{
output += "[" + current.getData().toString() + "]";
current = current.getNext();
}
return output;
}
}
My node:
public class Node {
Node next;
Object data;
public Node(Object _data)
{
next = null;
data = _data;
}
public Node(Object _data, Node _next)
{
next = _next;
data = _data;
}
public Object getData()
{
return data;
}
public void setData(Object _data)
{
data = _data;
}
public Node getNext()
{
return next;
}
public void setNext(Node _next)
{
next = _next;
}
}
I'm trying to create a function to rotate a singly linked in list in Java. I have made two functions for left and right.
My left function seems to work, but not fully. For example. If my list contains the elements: 1 2 3
Then my rotateLeft will make the list into 2 3. The 1 will be gone. But it should come on the position of previous 3.
As for the rotateRight, the function is not functioning properly for some reason, been trying a few hours and can't find the solution.
LinkedList LL = new LinkedList();
LL.add("1");
LL.add("2");
LL.add("3");
LL.add("4");
LL.add("4");
LL.add("5");
LL.rotateLeft();
2, 3, 4, 4, 5, null is the output. My add method is the following:
public void add(Object data)
{
Node temp = new Node(data);
Node current = head;
while(current.getNext() != null)
{
current = current.getNext();
}
current.setNext(temp);
listCount++;
}
Try this correction:
public void rotateLeft() {
if (head != null) { //otherwise it is empty list
Node temp = head;
if (head.getNext() != null) { //otherwise it is single item list
head = head.getNext();
}
Node tail;
if (head.getNext() != null) {
//more than 2 items in the list
tail = head.getNext();
} else {
//only 2 items in the list
tail = head;
}
while (tail.getNext() != null) {
if (tail.getNext() != null) {
tail = tail.getNext();
}
}
tail.setNext(temp);
temp.setNext(null);
}
}
public void rotateRight() {
if (head != null) { //otherwise it is empty list
Node tail = null;
Node current = head;
while (current.getNext() != null) {
tail = current;
current = current.getNext();
}
if (tail != null) { //otherwise it is single item list
tail.setNext(null);
current.setNext(head);
head = current;
}
}
}
You also did not treat the case of empty list, single item list or only 2 items in the list.
EDIT:
code:
public class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public LinkedList(Node head) {
this.head = head;
}
public void rotateLeft() {
System.out.println("<-");
if (head != null) { // otherwise it is empty list
Node temp = head;
if (head.getNext() != null) { // otherwise it is single item list
head = head.getNext();
}
Node tail;
if (head.getNext() != null) {
// more than 2 items in the list
tail = head.getNext();
} else {
// only 2 items in the list
tail = head;
}
while (tail.getNext() != null) {
if (tail.getNext() != null) {
tail = tail.getNext();
}
}
tail.setNext(temp);
temp.setNext(null);
}
}
public void rotateRight() {
System.out.println("->");
if (head != null) { // otherwise it is empty list
Node tail = null;
Node current = head;
while (current.getNext() != null) {
tail = current;
current = current.getNext();
}
if (tail != null) { // otherwise it is single item list
tail.setNext(null);
current.setNext(head);
head = current;
}
}
}
public void printList() {
Node cursor = head;
while (cursor != null) {
System.out.print(cursor.data + ", ");
cursor = cursor.getNext();
}
System.out.println();
}
public void add(Object data) {
Node temp = new Node(data);
if (head == null) {
head = temp;
} else {
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
}
}
public static void main(String[] args) {
LinkedList r = new LinkedList();
r.add(1);
r.add(2);
r.add(3);
r.add(4);
r.add(4);
r.add(5);
r.printList();
r.rotateLeft();
r.printList();
r.rotateLeft();
r.printList();
r.rotateRight();
r.printList();
r.rotateRight();
r.printList();
}
}
output:
1, 2, 3, 4, 4, 5,
<-
2, 3, 4, 4, 5, 1,
<-
3, 4, 4, 5, 1, 2,
->
2, 3, 4, 4, 5, 1,
->
1, 2, 3, 4, 4, 5,

Linked list node pointing to nodes of different type

This is my first post here, but I'm not new to the site (call me a lurker).
Unfortunately this time I cannot seem to find an answer to my question without asking.
Anyway, to the point.
I am writing a small snakes and ladders (aka chutes and ladders) program in java for a data structures course. I had to write my own Linked List (LL) class, (I know that there is a java util that does it better, but I have to learn about the workings of the data structure) and that is not a problem. My LL is 'semi-Double linked' as I like to call it, since it links forward, but has another pointer field for other links, which is not necessarily used in every node.
What I want to know is if it is possible to link a node from a list to another list, which is of a different type.
Poor example:
(eg.) How would one link a node of type to a node of type ? Let us say we have a LL of 7 int values [1,2,3,4,5,6,7], and a LL of 7 Strings [Monday, Tuesday, Wednesday,Thursday, Friday, Saturday, Sunday]. We want to link the node containing 1 to the node containing Monday.
To be exact the problem I am having is as follows:
I have 100 nodes forward-linked, forming the game board, and a circularly linked list of 4 . I want to link the player nodes to their respective positions on the board, so that as they traverse the board, they can also follow the "snakes" and "ladders" links.
Thanks in advance!
My LLNode.java and LL.java are attached.
// LLNode.java
// node in a generic linked list class, with a link
public class LLNode<T>
{
public T info;
public LLNode<T> next, link;
public LLNode()
{
next = null;
link= null;
}
public LLNode(T element)
{
info = element;
next = null;
link = null;
}
public LLNode(T element, LLNode<T> n)
{
info = element;
next = n;
link = null;
}
public T getInfo()
{
return info;
}
public void setInfo(T element)
{
info = element;
}
public LLNode<T> getNext()
{
return next;
}
public void setNext(LLNode<T> newNext)
{
next = newNext;
}
public LLNode<T> getLink()
{
return link;
}
public void setLink(LLNode<T> newLink)
{
link = newLink;
}
}
// SLL.java
// a generic linked list class
public class LL<T>
{
private LLNode<T> head, tail;
public LLNode<T> current = head;
public LL()
{
head = tail = null;
}
public boolean isEmpty()
{
return head == tail;
}
public void setToNull()
{
head = tail = null;
}
public boolean isNull()
{
if(head == tail)
if(head == null || tail == null)
return true;
else
return false;
else
return false;
}
public void addToHead(T element)
{
head = new LLNode<T>(element, head);
if (tail == null)
tail = head;
}
public void addNodeToHead(LLNode<T> newNode)
{
head = newNode;
if (tail == null)
tail = head;
}
public void addToTail(T element)
{
if (!isNull())
{
tail.next= new LLNode<T>(element);
tail = tail.next;
}
else head = tail = new LLNode<T>(element);
}
public void addNodeToTail(LLNode<T> newNode)
{
if (!isNull())
{
tail.next= newNode;
tail = tail.next;
}
else head = tail = newNode;
}
public void addBefore(T element, T X)
{
if (!isEmpty()) // Case 1
{
LLNode<T> temp, n;
temp = head;
while( temp.next != null )
{
if( temp.next.info == X )
{
n = new LLNode<T>(element, temp.next);
temp.next = n;
return;
}
else
temp = temp.next;
}
}
else // Case 2
head = new LLNode<T>(element, head);
}
public void addBefore(T element, LLNode<T> X)
{
if (!isEmpty()) // Case 1
{
LLNode<T> temp, n;
temp = head;
while( temp.next != null )
{
if( temp.next == X )
{
n = new LLNode<T>(element, X);
temp.next = n;
return;
}
else
temp = temp.next;
}
}
else // Case 2
head = new LLNode<T>(element, head);
}
public T deleteFromHead()
{
if (isEmpty())
return null;
T element = head.info;
if (head == tail)
head = tail = null;
else head = head.next;
return element;
}
public T deleteFromTail()
{
if (isEmpty())
return null;
T element = tail.info;
if (head == tail)
head = tail = null;
else
{
LLNode<T> temp;
for (temp = head; temp.next != tail; temp = temp.next);
tail = temp;
tail.next = null;
}
return element;
}
public void delete(T element)
{
if (!isEmpty())
if (head == tail && (element.toString()).equals(head.info.toString()))
head = tail = null;
else if ((element.toString()).equals(head.info.toString()))
head = head.next;
else
{
LLNode<T> pred, temp;
for (pred = head, temp = head.next; temp != null && !((temp.info.toString()).equals(element.toString())); pred = pred.next, temp = temp.next);
if (temp != null)
pred.next = temp.next;
if (temp == tail)
tail = pred;
}
}
public void listAll()
{
if(isNull())
System.out.println("\tEmpty");
else
{
for ( LLNode<T> temp = head; temp!= tail.next; temp = temp.next)
System.out.println(temp.info);
}
}
public LLNode<T> isInList(T element)
{
LLNode<T> temp;
for ( temp = head; temp != null && !((temp.info.toString()).equals(element.toString())); temp = temp.next);
return temp ;
}
public LLNode<T> getHead()
{
return head;
}
public LLNode<T> getTail()
{
return tail;
}
public LLNode<T> getCurrent()
{
return current;
}
public void incrementCurrent()
{
current = current.next;
}
public void followCurrentLink()
{
current = current.link;
}
}
Any specific reason you want to generics for the specific problem domain of the node objects?
If you want to have this effect, another way to do it might be have an interface for node object (maybe call it ILinkNode), have the getInfo and setInfo overridden in two different node classes. Then the nodeLink can point to interface object without special type casting everywhere in the code.
Use in the first list, i.e. the one containing the node you want to link to the node in the other list, Object as the generic type instantiation.
Something like:
LL<Object> ll = new LL<Object>();
If you do this, you have to take care to cast to the specific type, each time you retrieve a node's value from the list.

Categories