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,
Related
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
I am trying to use insertion sort to sort a doubly linked list. Before sorting, the doubly linked list has the following elements in the following order: 4, 1, 7, 10. The output it supposed to be 1, 4, 7, 10 (basically use the insertionSort method to sort the elements in ascending order).
delete - deletes a node and returns its value
insertAfter(Node n, val v) - inserts a new node with value v after node n
I've tried researching but haven't found anything to solve this.
Can anyone please help me?
import java.util.ArrayList;
public class DLinkedList {
private class Node {
private int value;
private Node nextNode;
private Node prevNode;
public Node(int v) {
value = v;
nextNode = null;
prevNode = null;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node n) {
nextNode = n;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node n) {
prevNode = n;
}
}
// Holds a reference to the head and tail of the list
private Node headNode;
private Node tailNode;
public DLinkedList() {
headNode = null;
tailNode = null;
}
public void addAtHead(int o) {
Node newNode = new Node(o);
newNode.setNextNode(headNode);
if (headNode != null)
headNode.setPrevNode(newNode);
headNode = newNode;
// special case for empty list
if (tailNode == null)
tailNode = newNode;
}
public void addAtTail(int o) {
Node newNode = new Node(o);
// this means that headNode == null too!
if(tailNode == null){
tailNode = newNode;
headNode = newNode;
}else{
newNode.setPrevNode(tailNode);
tailNode.setNextNode(newNode);
tailNode = newNode;
}
}
public int deleteAtHead() {
// list is empty
if(headNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = headNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = headNode.getValue();
headNode = headNode.getNextNode();
headNode.setPrevNode(null);
return res;
}
public int deleteAtTail() {
// list is empty
if(tailNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = tailNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = tailNode.getValue();
tailNode = tailNode.getPrevNode();
tailNode.setNextNode(null);
return res;
}
public int delete(Node n) {
if (n == null)
return -1;
Node next = n.getNextNode();
Node prev = n.getPrevNode();
int val = n.getValue();
if (prev != null)
prev.setNextNode(next);
if (next != null)
next.setPrevNode(prev);
// deleting at the end
if (n == tailNode)
tailNode = prev;
// deleteing at beginning
if (n == headNode)
headNode = next;
return val;
}
public void insertAfter(Node n, int val) {
if (n == null) { // this is the headNode
addAtHead(val);
return;
}
Node next = n.getNextNode();
Node newNode = new Node(val);
newNode.setPrevNode(n);
newNode.setNextNode(next);
n.setNextNode(newNode);
if (next == null) { // insert at tail
tailNode = newNode;
} else {
next.setPrevNode(newNode);
}
}
// computes the size of the list
public int size() {
if (headNode == null)
return 0;
Node n = headNode;
int size = 0;
while (n != null) {
size++;
n = n.getNextNode();
}
return size;
}
// Predicate to check if the linked list is sorted
public boolean isSorted() {
if (headNode == null || headNode.nextNode == null)
return true;
Node i = headNode.nextNode;
while (i != null) {
if (i.getValue() < i.getPrevNode().getValue())
return false;
i = i.nextNode;
}
return true;
}
// toString methods to override printing of object
public String toString() {
Node n = headNode;
StringBuffer buf = new StringBuffer();
while (n != null) {
buf.append(n.getValue());
buf.append(" ");
n = n.getNextNode();
}
return buf.toString();
}
public static void main(String[] args) {
DLinkedList d = new DLinkedList();
d.addAtHead(4);
d.addAtHead(1);
d.addAtHead(7);
d.addAtHead(10);
System.out.println("Before sorting: " + d); // this will call the toString method
d.insertionSort();
System.out.println("After sorting: " + d);
}
}
So if you want the list to be sorted why go with sorting at the end ? What I prefer is to insert them in the sorted way. So each time an element is inserted, its inserted in a sorted form.
Here is the working code:
import java.util.ArrayList;
public class DLinkedList {
private class Node {
private int value;
private Node nextNode;
private Node prevNode;
public Node(int v) {
value = v;
nextNode = null;
prevNode = null;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node n) {
nextNode = n;
}
public Node getPrevNode() {
return prevNode;
}
public void setPrevNode(Node n) {
prevNode = n;
}
}
// Holds a reference to the head and tail of the list
private Node headNode;
private Node tailNode;
public DLinkedList() {
headNode = null;
tailNode = null;
}
public void addAtHead(int o) {
Node newNode = new Node(o);
newNode.setNextNode(headNode);
if (headNode != null)
headNode.setPrevNode(newNode);
headNode = newNode;
// special case for empty list
if (tailNode == null)
tailNode = newNode;
}
public void addAtTail(int o) {
Node newNode = new Node(o);
// this means that headNode == null too!
if(tailNode == null){
tailNode = newNode;
headNode = newNode;
}else{
newNode.setPrevNode(tailNode);
tailNode.setNextNode(newNode);
tailNode = newNode;
}
}
public int deleteAtHead() {
// list is empty
if(headNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = headNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = headNode.getValue();
headNode = headNode.getNextNode();
headNode.setPrevNode(null);
return res;
}
public int deleteAtTail() {
// list is empty
if(tailNode == null){
headNode = null;
tailNode = null;
return -1;
}
// singleton: must update tailnode too
if(headNode == tailNode){
int res = tailNode.getValue();
headNode = null;
tailNode = null;
return res;
}
int res = tailNode.getValue();
tailNode = tailNode.getPrevNode();
tailNode.setNextNode(null);
return res;
}
public int delete(Node n) {
if (n == null)
return -1;
Node next = n.getNextNode();
Node prev = n.getPrevNode();
int val = n.getValue();
if (prev != null)
prev.setNextNode(next);
if (next != null)
next.setPrevNode(prev);
// deleting at the end
if (n == tailNode)
tailNode = prev;
// deleteing at beginning
if (n == headNode)
headNode = next;
return val;
}
public void insertAfter(Node n, int val) {
if (n == null) { // this is the headNode
addAtHead(val);
return;
}
Node next = n.getNextNode();
Node newNode = new Node(val);
newNode.setPrevNode(n);
newNode.setNextNode(next);
n.setNextNode(newNode);
if (next == null) { // insert at tail
tailNode = newNode;
} else {
next.setPrevNode(newNode);
}
}
// computes the size of the list
public int size() {
if (headNode == null)
return 0;
Node n = headNode;
int size = 0;
while (n != null) {
size++;
n = n.getNextNode();
}
return size;
}
// Predicate to check if the linked list is sorted
public boolean isSorted() {
if (headNode == null || headNode.nextNode == null)
return true;
Node i = headNode.nextNode;
while (i != null) {
if (i.getValue() < i.getPrevNode().getValue())
return false;
i = i.nextNode;
}
return true;
}
// toString methods to override printing of object
public String toString()
{
Node n = headNode;
StringBuffer buf = new StringBuffer();
while (n != null) {
buf.append(n.getValue());
buf.append(" ");
n = n.getNextNode();
}
return buf.toString();
}
// Insert in sorted for so you dont have to sort it after words
public void sortedInsert(int insertItem){
Node newNode = new Node(insertItem);
if(headNode == null){
headNode = tailNode = newNode;
return;
}
else {
Node temp = new Node(insertItem);
Node current = headNode;
while((current != null) && current.getValue() < insertItem){
temp = current;
current = current.getNextNode();
}
if(current == headNode){
addAtHead(insertItem);
return;
}
if (current == null){
addAtTail(insertItem);
return;
}
temp.setNextNode(newNode);
newNode.setNextNode(current);
current.setPrevNode(newNode);
newNode.setPrevNode(temp);
}
}
public static void main(String[] args) {
DLinkedList d = new DLinkedList();
String beforeSort = "";
d.sortedInsert(4);
// you can add the number in the order they are inserted just to show what it will look like unsorted
beforeSort+=" 4";
d.sortedInsert(1);
beforeSort+=" 1";
d.sortedInsert(7);
beforeSort+=" 7";
d.sortedInsert(10);
beforeSort+=" 10";
System.out.println("Before sorting: " + beforeSort);
System.out.println("After sorting: " + d); // this will call the toString method
}
}
I'm making a Doubly Linked List that allows you to insert at the front and rear, as well as deleting any node from the list as long as it exists. The problem is that it doesn't work and gives off and either gives off a NullPointerException or it just says That Integer does not exist even though it does exist.The code is:
public class Numbers {
Node head = null; //Head of the list
Node tail = null; //end of the doubly list
int size = 0;
public void FrontInsert(int data) {
Node n = new Node();
if (head == null) {
head = n;
} else {
n.prev = head;
head.next = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node();
if (head == null) {
head = n;
tail = n;
} else {
n.next = tail;
tail.prev = n;
tail = n;
}
size++;
}
public void Delete(int x) {
if (size == 0) {
System.out.println("The list is empty.");
}
if (head.data == x) {
head = head.next;
if (head != null) {
head.prev = null;
}
size--;
return;
}
tmp = head;
while (tmp != null && tmp.data != x) {
tmp = tmp.next;
}
if (tmp == null) {
System.out.println("That integer does not exist.");
return;
}
if (tmp.data == x) {
tmp.prev.next = tmp.next;
if (tmp.next != null) {
tmp.next.prev = tmp.prev;
}
}
size--;
}
public void printList() {
while (head != null) {
System.out.print(head.data + " ");
head = head.prev;
}
}
public static void main(String[] args) {
Numbers nu = new Numbers();
}
class Node {
Node prev;
Node next;
int data;
public void Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}
Try this and check output
public class Numbers {
Node head = null;
Node tail = null;
int size = 0;
public void FrontInsert(int data) {
Node n = new Node(data);
if (head == null) { // first insert
head = n;
tail = n;
} else {
n.next = head;
head.prev = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = n;
} else {
n.prev = tail;
tail.next = n;
tail = n;
}
size++;
}
public void Delete(int index) { // index is the position to be remove
if (size == 0) {
System.out.println("The list is empty."); return;
}else if(index < 0 || index > size -1){
System.out.println("Index outOf Bound."); return;
}
Node currentNode = head;
for(int i = 1; i <= index ; i++){
currentNode = currentNode.next;
}
//remove
if (index == 0) {
currentNode.next.prev = null;
head = currentNode.next;
} else if (index == size - 1) {
currentNode.prev.next = null;
tail = currentNode.prev;
} else {
if (currentNode.prev != null) // Ensure its not header
currentNode.prev.next = currentNode.next;
if (currentNode.next != null) // Ensure its not tail
currentNode.next.prev = currentNode.prev;
}
size--;
}
public void printList() {
Node tmp = head;
while (tmp != null) {
System.out.print(tmp.data + " ");
tmp = tmp.next;
}
System.out.println();
}
public static void main(String[] args) {
Numbers nu = new Numbers();
nu.FrontInsert(1);nu.printList();
nu.FrontInsert(2);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
nu.RearInsert(3);nu.printList();
nu.RearInsert(3);nu.printList();
nu.FrontInsert(4);nu.printList();
System.out.println();
nu.Delete(4);
nu.printList();
}
class Node {
Node prev;
Node next;
int data;
public Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}
Well, your head and tail were mutually exclusive, i mean when you add something to the tail of the list, you were only giving one side reference not both side, you have to says
tail.next = n; n.prev = tail; and tail = n.
Here is a working code:
public class Numbers {
Node head = null; //Head of the list
Node tail = null; //end of the doubly list
int size = 0;
public void FrontInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = head;
} else {
n.next = head;
head.prev = n;
head = n;
}
size++;
}
public void RearInsert(int data) {
Node n = new Node(data);
if (head == null) {
head = n;
tail = head;
} else {
n.next = null;
tail.next = n;
n.prev = tail;
tail = n;
}
size++;
}
#SuppressWarnings("null")
public void Delete(int x) {
if (size == 0) {
System.out.println("The list is empty.");
return;
}
if (head.data == x) {
head = head.next;
if (head != null) {
head.prev = null;
}
size--;
return;
}
Node tmp = head;
while (true) {
if(tmp == null)
break;
if(tmp.data == x)
break;
System.out.println(tmp.data);
tmp = tmp.next;
}
if (tmp == null) {
System.out.println("That integer does not exist.");
return;
}
if (tmp.data == x) {
tmp.prev.next = tmp.next;
if (tmp.next != null) {
tmp.next.prev = tmp.prev;
}
}
size--;
}
public void printList() {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
public static void main(String[] args) {
Numbers nu = new Numbers();
nu.FrontInsert(2);
nu.FrontInsert(3);
nu.FrontInsert(6);
nu.RearInsert(8);
nu.RearInsert(20);
nu.Delete(8);
nu.printList();
// System.out.println(nu.head.data + "data");
// System.out.println(nu.head.next.data + "data");
}
class Node {
Node prev;
Node next;
private int data;
public Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
}
class Node {
int data;
Node next;
public Node(int a) {data = a; next = null;}
}
public class List {
public Node head;
public List () {
head = null;
}
public boolean isEmpty() {
return head == null;
}
public void insertAtFront(int a) {
Node node = new Node(a);
node.next = head;
head = node;
}
public void insertAtEnd(int a) {
Node node = new Node(a);
// this check cannot be omitted
// otherwise you get NullPointerException on an empty list.
if (head == null) {
insertAtFront(a);
return;
}
Node cur = head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
public void insertAfter(Node node, int a) {
Node newNode = new Node(a);
if (node == null) {
System.out.println("Oops...");
return;
}
newNode.next = node.next;
node.next = newNode;
}
public Node search(int a) {
Node cur = head;
while(cur != null && cur.data != a) cur = cur.next;
return cur;
}
public int deleteFirst() {
if (head == null) {
System.out.println("Oops...");
return -1;
}
Node node = head;
head = head.next;
node.next = null;
return node.data;
}
public int deleteLast() {
if (head == null || head.next == null)
return deleteFirst();
Node second = head;
Node cur = second.next;
// when the thile loop finishes,
// cur points to the last node.
while(cur.next != null) {
second = cur;
cur = cur.next;
}
second.next = null;
return cur.data;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Node cur = head;
while(cur != null) {
sb.append(cur.data);
if (cur.next != null) sb.append(", ");
cur = cur.next;
}
return sb.toString();
}
private Node merge(Node head1, Node head2) {
Node dummy = new Node(0);
Node tail = dummy;
while (head1 != null && head2 != null) {
if (head1.data < head2.data) {
tail.next = head1;
head1 = head1.next;
} else {
tail.next = head2;
head2 = head2.next;
}
tail = tail.next;
}
if (head1 != null) {
tail.next = head1;
} else {
tail.next = head2;
}
return dummy.next;
}
public Node mergesort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node mid = findMiddle(head);
Node right = mergesort(mid.next);
mid.next = null;
Node left = mergesort(head);
return merge(left, right);
}
private Node findMiddle(Node head) {
Node slow = head, fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public static void main(String[] args) {
List list = new List();
list.insertAtFront(37);
list.insertAtFront(99);
list.insertAtFront(12);
// the list at page 88 of the slides.
System.out.println(list);
list.insertAtFront(75);
System.out.println(list);
list.insertAtEnd(38);
System.out.println(list);
list.insertAfter(list.search(12), 85);
System.out.println(list);
list.mergesort(list.head);
System.out.println("after sorting: " + list + "\n");
System.out.println("delete the first, which is " + list.deleteFirst());
System.out.println(list);
System.out.println("delete the last, which is " + list.deleteLast());
System.out.println(list);
}
}
Here is my code for linked list in merge sort. However, only the rear part of the linked list was displayed. what is the problem....?
Using Intellij:
12, 99, 37
75, 12, 99, 37
75, 12, 99, 37, 38
75, 12, 85, 99, 37, 38
after sorting: 75, 85, 99
delete the first, which is 75
85, 99
delete the last, which is 99
85
while getting return from mergesort() in main method you are not changing the head of the list there.
So in your case the list is sorted but head remains 75 only and thing work right according to the code
In main method
Replace: list.mergesort(list.head);
with: list.head = list.mergesort(list.head);
I refactored your code, see below. Hopefully it's pretty self explanatory.
public class List {
public Node head;
public List () {
head = null;
}
public boolean isEmpty() {
return head == null;
}
public void insertAtFront(int a) {
Node node = new Node(a);
node.next = head;
head = node;
}
public void insertAtEnd(int a) {
Node node = new Node(a);
if (head == null) {
head = node;
}
else {
Node cur = head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
public void insertAfter(Node predecessor, int a) {
if (predecessor == null) {
throw new IllegalArgumentException("Predecessor cannot be null");
}
Node node = new Node(a);
node.next = predecessor.next;
predecessor.next = node;
}
/** returns null if a is not found */
public Node findFirst(int a) {
Node cur = head;
while(cur != null && cur.data != a) {
cur = cur.next;
}
return cur;
}
public int removeFirst() {
if (head == null) {
throw new IllegalArgumentException("Cannot remove from empty list");
}
Node node = head;
head = head.next;
node.next = null;
return node.data;
}
public int removeLast() {
if (head == null || head.next == null) {
return removeFirst();
}
Node cur = head;
while(cur.next.next != null) {
cur = cur.next;
}
int data = cur.next.data;
cur.next = null;
return data;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Node cur = head;
while(cur != null) {
sb.append(cur.data);
if (cur.next != null) {
sb.append(", ");
}
cur = cur.next;
}
sb.append("]");
return sb.toString();
}
private Node merge(Node head1, Node head2) {
Node dummy = new Node(0);
Node tail = dummy;
while (head1 != null && head2 != null) {
if (head1.data < head2.data) {
tail.next = head1;
head1 = head1.next;
} else {
tail.next = head2;
head2 = head2.next;
}
tail = tail.next;
}
if (head1 != null) {
tail.next = head1;
} else {
tail.next = head2;
}
return dummy.next;
}
public Node mergesort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node mid = findMiddle(head);
Node right = mergesort(mid.next);
mid.next = null;
Node left = mergesort(head);
return merge(left, right);
}
private Node findMiddle(Node head) {
Node slow = head, fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public static void main(String[] args) {
List list = new List();
list.insertAtFront(37);
list.insertAtFront(99);
list.insertAtFront(12);
// the list at page 88 of the slides.
System.out.println(list);
list.insertAtFront(75);
System.out.println(list);
list.insertAtEnd(38);
System.out.println(list);
list.insertAfter(list.search(12), 85);
System.out.println(list);
list.head = list.mergesort(list.head);
System.out.println("after sorting: " + list + "\n");
System.out.println("delete the first, which is " + list.deleteFirst());
System.out.println(list);
System.out.println("delete the last, which is " + list.deleteLast());
System.out.println(list);
}
}
Returning -1 for failed removal is a bad idea since you are not preventing negative numbers as actual data.
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;
}
}