Insert Node at end of doubly linked list - java

I am trying to insert a node at the end of doubly linked list but when I run the add method, the code never finishes running. Here is the code below:
public class DoublyLinkedList<T> {
static class Node<T> {
T data;
Node<T> next;
Node<T> previous;
Node() {
data = null;
next = null;
previous = null;
}
Node(T value) {
data = value;
next = null;
previous = null;
}
}
private Node<T> head;
private int size;
public DoublyLinkedList() {
head = null;
}
public DoublyLinkedList(T value) {
head = new Node<T>(value);
size ++;
}
public void add(T value) {
Node<T> append = new Node<T>(value);
append.next = null;
if(head == null) {
append.previous = null;
head = append;
size ++;
return;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = append;
append.previous = current;
size ++;
}
I pretty sure the line that says current.next = append is the problem, but I am not sure how to fix it. What am I doing wrong?

Related

(JAVA) How do I Remove the First Element in a Circular Doubly Linked List?

I've managed to make the doubly linked list into a circular one, I'm just having trouble making a method to remove the first element. I've tried looking at examples for single linked lists but I can't seem to modify it to fit my code. Any help would be greatly appreciated.
Linkedlist Class
package LinkedListS;
public class LinkedList {
private Node first;
private Node end;
LinkedList()
{
first = end = null;
}
public void addAtStart(int x){
Node temp = new Node(x);
if(first == null)
{
first = end = temp;
}
else
{
end.setNext(temp);
temp.setNext(first);
first = temp;
}
}
public void printFromStart()
{
Node temp = first;
do {
System.out.println(temp.getData());
temp = temp.getNext();
end.setNext(null);
} while (temp != null);
}
public void searchFromStart(int elementToBeSearched)
{
Node temp = first;
while(temp != null)
{
if (temp.getData() == elementToBeSearched)
{
System.out.println("Found " + elementToBeSearched);
return;
}
temp = temp.getNext();
}
System.out.println("Didn't find " + elementToBeSearched);
}
public void removeFirstElement(){
}
Driver Class:
enter code here
public class LinkedListMain {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("Going to add elements At Start");
ll.addAtStart(5);
ll.addAtStart(7);
ll.addAtStart(9);
ll.addAtStart(10);
System.out.println("Print the doubly linked list elements");
ll.printFromStart();
System.out.println("Search the following elements");
ll.searchFromStart(7);
ll.searchFromStart(1289);
ll.removeFirstElement();
ll.printFromStart();
}
}
Node Class:
package LinkedListS;
public class Node {
private int data;
private Node next;
private Node prev;
// Constructor to intialize/fill data
public Node(int data)
{
this.data = data;
}
// set the address of next node
public void setNext(Node temp)
{
this.next = temp;
}
// get the address of next node
public Node getNext()
{
return this.next;
}
public Node getPrev()
{
return this.prev;
}
public void setPrev(Node temp)
{
this.prev = temp;
}
// to get data of current node
public int getData()
{
return this.data;
}
}
For the removeFirstElement method I've tried these solutions with no avail:
Attempt #1
Node temp = first;
temp = null;
Attempt #2
Node temp = first;
if(first != null){
if(temp.getNext() == first){
first = null;
}
} else {
first = end;
end = first.getNext();
}
Attempt #3
Node temp = first;
if (first == null) {
System.out.println("There is no first element to remove");
} else
temp = first;
System.out.println(temp);
Attempt #4
Node temp = first;
end = null;
if(first != null){
if(temp.getNext() == temp){
first = null;
}
} else {
end = first;
first = first.getNext();
}
After scanning a few other methods that is what I found that works:
public void removeFirstElement(){
if (first != null){
first = first.getNext();
} else {
System.out.println("There is nothing to be removed");
}
}

Doubly Linked List - RemoveFirst Method

I need help with following Code:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (!isEmpty()) {
if (head == tail) {
head = tail = null;
}
} else {
}
size--;
return false;
}
And this is my task:
"removes the first occurrence of the specified value from this list"
It s a method of a Doubly Linked List.
So far I think I did correct but I am still missing the "else" part and I have no clue what to put inside...
I also have a class with a constructor and getter- and setter- methods.
Here is my node class:
public class ListElement {
private Integer value;
private ListElement next;
private ListElement prev;
public ListElement(ListElement prev, Integer value, ListElement next) {
this.value = value;
this.next = next;
this.prev = prev;
}
public Integer getValue() {
return value;
}
public ListElement getNext() {
return next;
}
public ListElement getPrev() {
return prev;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(ListElement next) {
this.next = next;
}
public void setPrev(ListElement prev) {
this.prev = prev;
}
}
I am assuming by the function signature that you want to delete the element with the specific value. You need to find that node and remove it:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
ListElement found = head;
// Try to find it
while (null != found && !found.value.equals(value)) {
found = found.next;
}
// Not found?
if (null == found) {
throw new NoSuchElementException();
}
// Found. Unlink
if (found.prev != null) found.prev.next = found.next;
else head = found.next;
if (found.next != null) found.next.prev = found.prev;
else tail = found.prev;
size--;
return true;
}
Firstly, this if should be removed as you already test for empty
if (!isEmpty()) {
if (head == tail) {
head = tail = null;
}
} else {
}
Then you can process like:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (head == tail) {
if (head.getValue() == value) {
head = tail = null;
} else {
// Not found, return false
size--;
return false;
}
}
ListElement current = head;
while (current != null) {
if (current.getValue() == value) {
// Found
if (current.getPrev() == null) {
// current node is head node
head = current.getNext();
current.setPrev(null);
} else if (current.next() == null) {
// current node is tail node
tail = current;
current.setNext(null);
} else {
// Current node is in the middle
ListElement prev = current.getPrev();
ListElement next = current.getNext();
prev.setNext(next);
next.setPrev(prev);
}
size--;
return true;
}
}
// Not found
size--;
return false;
}

Rotating a Linked List Clockwise

I want to rotate my linked list clockwise by a certain amount.
private class Node {
private T data; // Entry in bag
private Node next; // link to next node
private Node(T dataPortion) {
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
} // end Node
public void leftShift(int num){
if (num == 0) return;
Node current = firstNode;
int count = 1;
while (count < num && current != null)
{
current = current.next;
count++;
}
if (current == null)
return;
Node kthNode = current;
while (current.next != null)
current = current.next;
current.next = firstNode;
firstNode = kthNode.next;
kthNode.next = null;
}
I managed to get my counter clockwise rotation to work but I'm kinda confused about how to get the clockwise rotation since I can't find previous nodes.
The example you asked:
private class Node {
private T data; // Entry in bag
private Node next; // link to next node
public Node(T dataPortion) {
this(dataPortion, null);
} // end constructor
public Node(T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
T getObject() {
return data;
}
Node<T> getNext() {
return next;
}
} // end Node
public class Queue<T>{
 
private Node head;
private Node tail;
private String name;
public Queue(){
this("queue");
}
 
public Queue(String listName) {
name = listName;
head = tail = null;
}
public boolean isEmpty() {
return tail == null;
}
public void put(T item) {
Node node = new Node(item);
if (isEmpty()) // head and tail refer to same object
head = tail = node;
else { // head refers to new node
Node oldtail= tail;
tail=node;
oldtail.nextNode=tail;
}
}
public Object get() throws NoSuchElementException {
if (isEmpty()) // throw exception if List is empty
throw new NoSuchElementException();
 
T removedItem = head.data; // retrieve data being removed
 
// update references head and tail
if (head == tail)
head = tail = null;
else // locate new last node
{
head=head.nextNode;
} // end else
 
return removedItem; // return removed node data
}
public int size() {
int count = 0;
if(isEmpty()) return count;
else{
Node<T> current = head;
// loop while current node does not refer to tail
while (current != null){
count++;
if(current.nextNode==null)break;
current=current.nextNode;
}
return count;
}
public void shift(){
if(size()<=1)return;
T removed = get();
put(removed);
}
}
ListNode* Solution::rotateRight(ListNode* A, int B) {
if(A==NULL) return NULL;
ListNode *cur=A;
int len=1;
while(cur->next!=NULL){
cur=cur->next;
len++;
}
cur->next=A;
int preLen=len-B%len-1;
ListNode *pre=A;
while(preLen--)
pre=pre->next;
A=pre->next;
pre->next=NULL;
return A;
}

Priority Queue Generic

So I recently learnt about Generics and thought it would be cool to implement them in a Priority Queue. I am having a "Block" element which has a firstName and a data variable. The Node for the Priority Queue consists of Block, Next and Prev.
I am attaching the code below. I am almost exclusively getting "Should be parametrized" errors/warnings. And an error which says that my "Data" element cannot be resolved to a field, which probably means that I am unable to tell that I want Block as my "element E" in a Node. Any suggestions will be deeply appreciated
package QGen;
public class Block<E> implements Comparable<Block<E>> {
protected String firstName;
protected int data;
public Block(String firstName, int data) {
super();
this.firstName = firstName;
this.data = data;
}
#Override
public int compareTo(Block x) {
return (this.data - x.data);
}
}
package QGen;
public class PriorityQueue<E extends Comparable> {
protected Node<E> firstSentinel;
protected Node<E> lastSentinel;
protected class Node<E> {
protected Node<E> next;
protected Node<E> prev;
private E element;
public Node(E e, Node<E> previous, Node<E> nextt) {
element = e;
prev = previous;
next = nextt;
}
}
public PriorityQueue() {
firstSentinel = new Node<>(null, null, null);
lastSentinel = new Node<>(null, null, null);
firstSentinel.data = 11111;
lastSentinel.data = 0;
firstSentinel.prev = null;
firstSentinel.next = lastSentinel;
lastSentinel.prev = firstSentinel;
lastSentinel.next = null;
}
public void enQueue(E x) {
Node<E> newX = new Node<E>(x, null, null);
if (firstSentinel.next == lastSentinel)// list is empyty
{
firstSentinel.next = newX;
newX.prev = firstSentinel;
newX.next = lastSentinel;
lastSentinel.prev = newX;
} else {
Node<E> temp = newX;
Node<E> curr = firstSentinel.next;
while (curr != lastSentinel && temp.element.compareTo(curr) <= 0) {// <=comparison
// replaced
curr = curr.next;
}
Node<E> tempCurr = curr;
temp.next = tempCurr;
temp.prev = tempCurr.prev;
tempCurr.prev.next = temp;
tempCurr.prev = temp;
}
}
public E deQueue() {
if (firstSentinel.next == lastSentinel) {
return null;
} else {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
firstSentinel.next = temp.next;
temp.next.prev = firstSentinel;
return temp.element;
}
}
public void printt() {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
while (temp != lastSentinel) {
System.out
.println(temp.element.firstName + " " + temp.element.data);
temp = temp.next;
}
}
}
package QGen;
public class containsMain<E> {
public static void main(String[] args) {
PriorityQueue<Block> example = new PriorityQueue<Block>();
Block dequedObject = new Block<>(null, null);
Block<Block> incomingName = new Block<>("r", 1);
example.enQueue(incomingName);
dequedObject = (Block) example.deQueue();
}
}
I am aware that my PriorityQueue might not be the best of implementations and I will improve it. It is the Generics where I am unable to come up with a solution
Thanks
Without looking at the logic of your methods, I have several remarks regarding generics:
why is Block itself generic? It doesnt hold any generic field so remove it from Block!
new Node<>(null, null, null);
// this is a bad idea, change it to new Node<E>(null, null, null)
firstSentinel.data = 11111;
lastSentinel.data = 0;
//Those two cant work, because firstSentinel is referencing a Node<E> and not a Block! Delete those two rows, as they make no sense in your generic implementation of the Queue
Block<Block> incomingName = new Block<>("r", 1);
// This doesnt make sense, should be Block incomingName = new Block(...)

How to check if member exists

So i have implemented the insert method and it works just fine but my problem is how to check whether a member is already in the list or not,i want the program to check if the member is already in the list but the checker doesn't work. i want the program to put the member in team1 if the member is included in the list and Display "member does not exist" if the member is not on the list. I made a check method but it doesn't work. I am new in Programming and i really need help. Please enlighten me with your knowledge.
class Node
{
protected String info;
protected Node next;
public Node(String value)
{
info = value;
next = null;
}
}
class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
head = null;
count = 0;
}
public void insert( String name)
{
Node a = new Node(name);
a.next = null;
count++;
if (head == null)
{
head = a;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = a;
return;
}
}
}
public void checker(String name)
{
for(Node cur = head; cur != null; cur = cur.next)
{
if(cur.info == name)
{
insertteam1(name);
System.out.print("OK");
}
else
{
System.out.print("member does not exist");
}
}
}
public void insertteam1(String name)
{
Node b = new Node(name);
b.next = null;
count++;
if (head == null)
{
head = b;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = b;
return;
}
}
}
In the code below,
if(cur.info == name){ // }
you are comparing the string info using == which is not the right way to compare strings in java.
Use
if(cur.info.equals(name)){ // }
or
use if(cur.info.equalsIgnoreCase(name)){ // } if you want to do case insensitive compare.

Categories