Rotating a Linked List Clockwise - java

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;
}

Related

How to link the a circular linked list tail to the head of the list in Java?

I'm trying to insert at the front and insert at the back of the list. However, I've got those methods to work to a certain extent in the Circular Linked List class.
My problem is, I can't seem to figure out how to link the tail with the head of the list. I have got the head to point to the tail though.
So after executing the below lines of code:
list.InsertAtFront(0);
list.InsertAfter(0, 4); // Inserting the 4 after 0 which was inserted above...
The result I got was
[Data: ID = 0 |{Previous: 4}, {Next: 4}] -> [Data: ID = 4 |{Previous: 0}, {Next: null}]
What should be here for the second insert, Where next is pointing to null {Next: null} it should be pointing the the head of the list {Next: 0}.
I would really appreciate the help guys!
I'll show what I have so far below...
THE NODE CLASS
package circular_linked_list;
public class Node {
private int id;
private Node next_node;
private Node previous_node;
public Node(){
this.id = 0;
this.next_node = null;
this.previous_node = null;
}
public Node(int id, Node next_node, Node previous_node){
this.id = id;
this.next_node = next_node;
this.previous_node = previous_node;
}
public Node(int id){
this.id = id;
this.next_node = null;
this.previous_node = null;
}
public Node(Node node){
this.id = node.GetId();
this.next_node = node.GetNextNode();
this.previous_node = node.GetPreviousNode();
}
public void SetId(int id) {
this.id = id;
}
public void SetNextNode(Node next_node) {
this.next_node = next_node;
}
public void SetPreviousNode(Node previous_node) {
this.previous_node = previous_node;
}
public int GetId() {
return this.id;
}
public Node GetNextNode() {
return this.next_node;
}
public Node GetPreviousNode() {
return this.previous_node;
}
public void NodeDetails(){
if(this.previous_node != null && this.next_node != null){
System.out.print("[Data: __ID = " + this.id + "__ |{Previous: " + this.previous_node.GetId() + "}, {Next: "+ this.next_node.GetId() + "}] -> ");
}
else if(this.previous_node != null){
System.out.print("[Data: __ID = " + this.id + "__ |{Previous: " + this.previous_node.GetId() + "}, {Next: null}] -> ");
}
else if(this.next_node != null){
System.out.print("[Data: __ID = " + this.id + "__ |{Previous: null}, {Next: "+ this.next_node.GetId() + "}] -> ");
}
else{
System.out.print("[Data: __ID = " + this.id + "__ |{Previous: null}, {Next: null}] -> ");
}
}
}
THE CIRCULAR LINKED LIST CLASS
package circular_linked_list;
public class CircularLinkedList{
private Node head;
private Node tail;
public CircularLinkedList(){
this.head = null;
this.tail = null;
}
public CircularLinkedList(Node head, Node tail){
this.head = head;
this.tail = tail;
}
public void SetHead(Node head){
this.head = head;
}
public void SetTail(Node tail){
this.tail = tail;
}
public Node GetHead(){
return this.head;
}
public Node GetTail(){
return this.tail;
}
public void InsertAtFront(int data){
Node new_node = new Node(data);
if( new_node != null){
// If the list is not empty then...
if(this.head != null){
this.head.SetPreviousNode(new_node); // Set the list head's previous node to point to the new node.
new_node.SetNextNode(this.head); // Set the new node's next node to point to the current list head.
new_node.SetPreviousNode(this.tail); // Set the previous node of the head of the list to point to the tail of the list
}
this.head = new_node; // Set the list head to point to the new node
this.FindTail(); // Set the tail of the list.
}
else{
System.out.print("Sorry, the list is full!");
}
}
public void InsertAfter(int target, int data){
Node new_node = new Node(data);
if(new_node != null){
Node target_node = this.head;
boolean found = false;
// This while loop will loop to find if a node is equal to the value passed as target.
while(target_node != null){
if(target_node.GetId() == target){
// If the target is found then break the loop to keep this current node as the target node.
found = true;
break;
}
// Assigning the target node next node to the target node.
target_node = target_node.GetNextNode();
}
// If the target was found then...
if(found){
new_node.SetPreviousNode(target_node); // Set the previous node of the new node to point to the target node.
// Set the next node of the new node with the target node's next node to continue to link.
new_node.SetNextNode(target_node.GetNextNode());
// If the target node's next node is not null, then set the target node's next node->previous node to point to the new node.
if(target_node.GetNextNode() != null){
target_node.GetNextNode().SetPreviousNode(new_node);
}
target_node.SetNextNode(new_node); // Set the target node's next node to point to the new node.
// Setting the tail of the list...
this.FindTail();
}
else{
System.out.println("Sorry, but the integer " + target + " was not found in the list!\n");
}
}
else{
System.out.println("Sorry, the list is full!\n");
}
}
public void DisplayList(){
Node current_node = this.head;
while(current_node != null){
current_node.NodeDetails();
current_node = current_node.GetNextNode();
}
}
private void FindTail(){
Node current_node = this.head;
// Traversing from the start of the list to the end to get the tail.
while(current_node.GetNextNode() != null){
current_node = current_node.GetNextNode();
}
this.head.SetPreviousNode(current_node); // Updating the head of the list previous node.
this.SetTail(current_node); // Set the tail of the list with the last node.
}
}
THE MAIN CLASS
package circular_linked_list;
public class Main {
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
// Inserting at the front of the list
list.InsertAtFront(0);
// Inserting 4 right after the 0
list.InsertAfter(0, 4);
// To display the nodes/elements in the list
list.DisplayList();
}
}
The main issue in your code is that you assume there will be a next reference that is null, but that is in contradiction with the principle of a circular linked list. In a circular linked list, you can always go from one node to the next and run endlessly in circles. So the principle is: none of the next references should be null!
This means you'll have to adapt your code at several places where you either set a null, or check against a null value.
Some other remarks:
Let the Node constructor make the new node refer to itself via its next and previous members. This way you avoid storing null there from the very start. It is like making a one-node circular linked list on its own.
The loops should not check for null, but instead detect that you have cycled around and got back to the head node.
There is some code repetition for the two flavours of insertion-methods you have. This linking of the new node with the existing nodes should be done at one place only. I suggest making a separate method for that.
There really is no need to have a tail member in your class, because that tail is always going to be this.head.GetPreviousNode() (unless of course your list is empty). So I would just drop that tail member and work with that expression instead. This will save you from keeping that tail reference up to date.
The insertAfter method currently performs a find for the target value in the list. It would be nicer, if you placed this logic in a separate find method, so it could be re-used elsewhere (if needed).
Here is the corrected Node class:
public class Node {
private int id;
private Node next_node;
private Node previous_node;
public Node(){
this.id = 0;
// Make a node refer to itself by default -- this is practical in a circular list
this.next_node = this;
this.previous_node = this;
}
public Node(int id, Node next_node, Node previous_node){
this.id = id;
this.next_node = next_node;
this.previous_node = previous_node;
}
public Node(int id){
this.id = id;
// Make a node refer to itself by default -- this is practical in a circular list
this.next_node = this;
this.previous_node = this;
}
public Node(Node node){
this.id = node.GetId();
this.next_node = node.GetNextNode();
this.previous_node = node.GetPreviousNode();
}
public void SetId(int id) {
this.id = id;
}
public void SetNextNode(Node next_node) {
this.next_node = next_node;
}
public void SetPreviousNode(Node previous_node) {
this.previous_node = previous_node;
}
public int GetId() {
return this.id;
}
public Node GetNextNode() {
return this.next_node;
}
public Node GetPreviousNode() {
return this.previous_node;
}
public void NodeDetails(){
System.out.print("[Data: __ID = " + this.id + "__ |{Previous: " + this.previous_node.GetId() + "}, {Next: "+ this.next_node.GetId() + "}] -> ");
}
}
And the corrected CircularLinkedList class:
public class CircularLinkedList{
private Node head; // No need for a tail
public CircularLinkedList(){
this.head = null;
}
public CircularLinkedList(Node head){
this.head = head;
}
public void SetHead(Node head){
this.head = head;
}
public Node GetHead(){
return this.head;
}
public void InsertAtFront(int data){
if (this.head == null) {
this.head = new Node(data);
} else {
insertAfter(this.head.GetPreviousNode(), data);
this.head = this.head.GetPreviousNode();
}
}
public Node find(int target) {
Node target_node = this.head;
while (target_node != null) {
if(target_node.GetId() == target) {
return target_node;
}
target_node = target_node.GetNextNode();
if (target_node == this.head) break; // running in circles
}
return null;
}
// Add this method to avoid code repetition
public void insertAfter(Node target_node, int data) {
Node new_node = new Node(data, target_node.GetNextNode(), target_node);
target_node.SetNextNode(new_node);
new_node.GetNextNode().SetPreviousNode(target_node);
}
public void InsertAfter(int target, int data){
Node target_node = find(target);
if (target_node != null) {
insertAfter(target_node, data);
} else{
System.out.println("Sorry, but the integer " + target + " was not found in the list!\n");
}
}
public void DisplayList(){
Node current_node = this.head;
while (current_node != null) {
current_node.NodeDetails();
current_node = current_node.GetNextNode();
if (current_node == this.head) break; // running in circles
}
}
}

(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");
}
}

Insert Node at end of doubly linked list

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?

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;
}

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