hello i am trying to generate a random doubly linkedlist but i have to insert the node with a negative value and its next node(value doesnt matter) to the HEAD of the list but when i compile the program i am stuck in an infinite loop with one repeating number.I think i connected the list wrong but i am not sure. For context LC is the NODE class, tete is head queue is tail, prev and suiv and next and previous pointer.
class LC {
public int data;
public LC suiv;
public LC prec;
}
public class ChainesDouble {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Détermine an even number N between 10 and 30
int N = (int)(Math.random()*16)+5;
N = (N*2);
System.out.println("La valeur de N = " + N);
// Create a doubly linkedlist with N elements
LC tete = null;
LC queue = null;
for (int i = 0; i < N/2; i++) {
int valeur = getRandom();
int next = getRandom();
//If the generated number is negative insert that number and
//next value into the head of the list
if(valeur <0) {
LC temp = new LC();
temp.data = valeur;
if(tete == null) {
queue = temp;
}
temp = new LC();
temp.data = next ;
tete.prec = temp ;
temp.suiv = tete ;
tete = temp ;
tete.prec = temp ;
temp.suiv = tete ;
tete = temp ;
//If the number is positive, insert the element and the
//next element into the TAIL of the list
}
else {
LC temp = new LC();
temp.data = valeur;
if(queue == null) {
tete = temp;
queue = temp;
}else {
temp.prec = queue;
queue.suiv = temp ;
queue = temp ;
}
temp.prec = queue;
queue.suiv = temp ;
queue = temp ;
}
}
public static int getRandom(){
int N = (int)(Math.random()*42);
if(N<21) {
N -=30;//Rand(-10;-30)
}
else {
N-=11;//Rand(10;30)
}
return N;
}
}
public static void main(String[] args) {
Random random = new Random();
int halfSize = random.nextInt(30) + 1;
ListNode head = createLinkedList(halfSize, random);
System.out.println(printToString(head));
}
private static String printToString(ListNode node) {
StringBuilder buf = new StringBuilder();
while (node != null) {
if (buf.length() > 0)
buf.append("->");
buf.append(node.value);
node = node.next;
}
return buf.toString();
}
public static ListNode createLinkedList(int halfSize, Random random) {
ListNode head = null;
ListNode tail = null;
for (int i = 0; i < halfSize; i++) {
int one = getRandomValue(random);
int two = getRandomValue(random);
if (one >= 0) {
tail = addTail(one, tail);
head = head == null ? tail : head;
tail = addTail(two, tail);
} else {
head = addHead(one, head);
head = addHead(two, head);
}
}
return head;
}
private static ListNode addHead(int value, ListNode head) {
ListNode node = new ListNode(value);
node.next = head;
if (head != null)
head.prev = node;
return node;
}
private static ListNode addTail(int value, ListNode tail) {
ListNode node = new ListNode(value);
node.prev = tail;
if (tail != null)
tail.next = node;
return node;
}
private static int getRandomValue(Random random) {
return (random.nextInt(30) + 1) * (random.nextBoolean() ? 1 : -1);
}
public static final class ListNode {
public final int value;
public ListNode next;
public ListNode prev;
public ListNode(int value) {
this.value = value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
I don't know if i got your requirements correctly. But here is a loop that would achieve a doubly linked list with your tete and queue. The comments explain the logic.
class LC {
public int data;
public LC suiv;
public LC prec;
}
public class ChainesDouble {
public static int getRandom(){
int N = (int)(Math.random()*42);
if(N<21) {
N -=30;
} else {
N-=11;
}
return N;
}
public static void main(String[] args) {
int N = (int)(Math.random()*16)+5;
N = (N*2);
System.out.println("La valeur de N = " + N);
LC tete = null;
LC queue = null;
for (int i = 0; i < N/2; i++) {
int valeur = getRandom();
int next = getRandom();
//get the two random values
LC temp_a = new LC();
LC temp_b = new LC();
//Store the data in the two nodes
temp_a.data = valeur;
temp_b.data = next ;
//link the two nodes
temp_a.suiv = temp_b;
temp_b.prec = temp_a;
//If the list is empty, then initialize tete(head) and queue(tail)
if(tete == null) {
tete = temp_a;
queue = temp_b;
} else {
if(valeur <0) { //If valeur is negative, add to tete
temp_b.suiv = tete;
tete.prec = temp_b;
tete = temp_a;
}
else { //If valeur is positive, add to queue
queue.suiv = temp_a;
temp_a.prec = queue;
queue = temp_b;
}
}
}
//Test Program
LC temp = tete;
while (temp!=null) {
System.out.println(temp.data);
temp=temp.suiv;
}
//Search for second multiple of 5
LC search = tete;
int count = 0;
boolean found = false;
while (search!=null) {
if (search.data%5==0)
count++;
if (count==2) {
found = true;
System.out.println("Found "+search.data);
break;
}
search = search.suiv;
}
//if found
if (found) {
int position = 5;
if (search.data%10==0) position = 10;
System.out.println("Position "+position);
//remove search for current position
if (search.suiv!=null) {
LC prev = search.prec;
LC next = search.suiv;
prev.suiv = next;
next.prec = prev;
} else {
search.prec.suiv = null;
}
//move pointer to desired position
LC move = tete;
int cur = 1;
while(move!=null) {
move = move.suiv;
cur++;
if (cur==(position - 1)) {
break;
}
}
System.out.println("shifting "+search.data+" to after "+move.data);
//link searched item into desired position
search.suiv = move.suiv;
move.suiv.prec = search;
move.suiv = search;
search.prec = move;
}
}
}
Related
I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.
Use an inner class for the Node.
Include the methods below.
Write a tester to enable you to test all of the methods with whatever data you want in any order.
I have to create a method called "public LinkedListOfInts reverse()". This method is meant to "Return a copy of your Linked List but in reverse order." I have my code for this method down below. However, when I try to reverse a list it only prints the head. For Example, if I have a list like "[16, 1, 8, 7, 10, 10, 14, 17, 11, 4,] and I try to reverse it my output is [ 16, ]. Does someone know how correct my code so I can reverse a linked list?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
if (head == null)
return null;
Node current = head;
Node previous = null;
Node nextNode = null;
while (current != null) {
nextNode = current.nextNode;
current.nextNode = previous;
previous = current;
current = nextNode;
}
return this;
}
public String toString() {
String result = " ";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result += ptr.value + " ";
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 11:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 12:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
Here is a working example for reversing your LinkedList. Keep in mind that you are not copying the content of the LinkedList. So if you reverse the list, the original list's head is now the tail and returns only one int.
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts{
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
#Override
public String toString() {
return "Node{" +
"value=" + value +
", nextNode=" + nextNode +
'}';
}
}
public LinkedListOfInts(LinkedListOfInts other) {
System.out.println(other.tail);
head = other.head;
tail = other.tail;
System.out.println(this);
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++) {
this.addToFront(random.nextInt(high - low) + low);
}
Node node=head;
while(node.nextNode!=null){
node = node.nextNode;
}
tail = node;
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
Node previous = null;
Node curr = head;
Node nex;
while (curr != null)
{
nex = curr.nextNode;
curr.nextNode = previous;
previous = curr;
curr = nex;
}
head = previous;
return this;
}
public String toString() {
StringBuilder result = new StringBuilder(" ");
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result.append(ptr.value).append(" ");
return result.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 2:
System.out.println("toString");
System.out.println(list);
break;
}
}
}
}
I'm trying to write a program that will go forwards in a circular doubly linked list a certain amount of times and backwards in the same list a certain amount of times. If both methods end up at the same number then the number is 'worthy' and is removed from the list. If the methods don't end up at the same element on the list then they are unworthy and are removed from the list as well. I've written the method for going forwards and backwards a certain amount of times but I'm having difficulty with removing the elements once they have been deemed worthy or unworthy. This is what I have so far. Any help would be greatly appreciated.
import java.util.Arrays;
public class LinkedList {
private Node head;
private Node end;
LinkedList(){
head = end = null;
}
public void addAtStart(int x){
if (head == null) {
Node new_node = new Node(x);
new_node.data = x;
new_node.next = new_node.prev = new_node;
head = new_node;
} else if (head != null) {
Node last = (head).prev;
Node new_node = new Node(x);
new_node.data = x;
new_node.next = head;
(head).prev = new_node;
new_node.prev = last;
last.next = new_node;
}
}
public void printOutput(int N, int k, int m){
System.out.println("Output" + "\n" + "------" + "\n");
printCandidates(N,k,m);
}
public void printCandidates(int N, int k, int m){
int unworthy[] = new int[N];
int worthy[] = new int[N];
int count = 0;
int run = 0;
Node temp = head;
do {
if (forwards(k) == backwards(m)){ // puts in worthy list and deletes from linked list
worthy[count] = forwards(k);
count += 1;
System.out.println("hello");
deleteElement(forwards(k));
} else if (forwards(k) != backwards(m)){ //put in unworthy list and delete from linked list
unworthy[run] = forwards(k);
unworthy[run+1] = backwards(m);
run += 2;
System.out.println("goodbye");
deleteElement(forwards(k));
deleteElement(backwards(m));
}
} while (temp != null);
System.out.println("Removed candidates from being elected");
System.out.println(Arrays.toString(unworthy));
System.out.println("Worthy candidates");
System.out.println(Arrays.toString(worthy));
}
int forwards(int k){
int run = 0;
int x = 0;
Node temp = head;
while (temp.next != head){
if(run == (k)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
int backwards(int m){
int run = 0;
int x = 0;
Node temp = head;
Node last = head.prev;
temp = last;
while (temp.next != head){
if(run == (m)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
public void deleteElement(int elementToBeDeleted){
Node temp = head;
while (temp.next != head){
if(temp.data == elementToBeDeleted){
temp.setNext(temp.next);
}
temp = temp.next;
}
}
This is my driver:
public class Program2 {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
for (int i = 1; i < 11; i++){
ll.addAtStart(i);
}
int N = 10;
int k = 4;
int m = 3;
System.out.println("N = " + N + ", " + "k = " + k + ", " + "m = " + m + "\n");
ll.printOutput(N,k,m);
}
}
This is my node class:
public class Node {
public int data;
public Node next;
public 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;
}
}
EDIT: As part of this exercise I need to write the class myself, therefore why I am implementing my own LinkedList.
public class SimpleLinkedList<E> {
public Node<E> head;
public int size;
public void add(E e) {
++this.size;
if (null == head) {
this.head = new Node();
head.val = e;
} else {
Node<E> newNode = new Node();
newNode.val = e;
newNode.next = head;
this.head = newNode;
}
}
public void swap(E val1, E val2) {
if (val1.equals(val2)) {
return;
}
Node prevX = null, curr1 = head;
while (curr1 != null && !curr1.val.equals(val1)) {
prevX = curr1;
curr1 = curr1.next;
}
Node prevY = null, curr2 = head;
while (curr2 != null && !curr2.val.equals(val2)) {
prevY = curr2;
curr2 = curr2.next;
}
if (curr1 == null || curr2 == null) {
return;
}
if (prevX == null) {
head = curr2;
} else {
prevX.next = curr2;
}
if (prevY == null) {
head = curr1;
} else {
prevY.next = curr1;
}
Node temp = curr1.next;
curr1.next = curr2.next;
curr2.next = temp;
}
public void reverse() {
Node<E> prev = null;
Node<E> current = head;
Node<E> next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
public static class Node<E> {
public Node<E> next;
public E val;
}
}
public class SimpleLinkedListTest {
#Test
public void testReverseMethod() {
SimpleLinkedList<Integer> myList = new SimpleLinkedList<>();
for (int i = 0; i < 10; i++) {
myList.add(i);
}
SimpleLinkedList<Integer> expectedList = new SimpleLinkedList<>();
for (int i = 9; i > -1; i--) {
expectedList.add(i);
}
myList.reverse();
assertTrue(AssertCustom.assertSLLEquals(expectedList, myList));
}
}
What would be the most optimal way to reverse generic LinkedList by using the swap method?
before reverse method :
(head=[9])->[8]->[7]->[6]->[5]->[4]->[3]->[2]->[1]->[0]-> null
after reverse() method :
(head=[0])->[1]->[2]->[3]->[4]->[5]->[6]->[7]->[8]->[9]-> null
What you need to do is divide the list in half. If the list size is odd the one in the middle will remain in place. Then swap elements on either side in a mirror like fashion. This should be more efficient than O(n^2)
reverse(){
Node current = this.head;
int half = this.size/2;
int midElement = this.size % 2 == 0 ? 0: half + 1;
Stack<Node<E>> stack = new Stack<Node<E>>();
for(int i = 0; i < this.size; i++){
if (i < = half)
stack.push(current);
else{
if (i == midElement)
continue;
else
swap(stack.pop(), current);
current = current.next;
}
}
swap(Node<E> v, Node<E> v1){
E tmp = v.value;
v.value = v1.value;
v1.value = tmp;
}
This is a little bit of pseudo java. It is missing still the checks for size = 0 or size = 1 when it should return immediately. One for loop. Time Complexity O(n). There is also the need to check when size = 2, swap(...) is to be invoked directly.
Based on the #efekctive 's idea, there a solution. The complexity is a little bit worse than O^2 but no need changes in the swap method, no need in usage of another collection. The code below passes the unit test, however, be careful to use it there could be a bug related to size/2 operation. Hope this help.
public void reverse() {
Node<E> current = head;
SimpleLinkedList<E> firstHalf = new SimpleLinkedList<>();
SimpleLinkedList<E> secondHalf = new SimpleLinkedList<>();
for (int i = 0; i < size; i++) {
if (i >= size / 2) {
firstHalf.add(current.val);
} else {
secondHalf.add(current.val);
}
current = current.next;
}
SimpleLinkedList<E> secondHalfReverse = new SimpleLinkedList<>();
for (int i = 0; i < secondHalf.size(); i++) {
secondHalfReverse.add(secondHalf.get(i));
}
for (int i = 0; i < size / 2; i++) {
if (secondHalfReverse.get(i) == firstHalf.get(i)) {
break;
}
swap(secondHalfReverse.get(i), firstHalf.get(i));
}
}
I am trying to add two non negative numbers, the digits of which are stored in reverse order in two separate linked lists. The answer should also be a linked list with digits reversed and no trailing zeros.
I understand that there is a way to solve this question by adding digits and maintaining a carry each time, but I am trying to solve it by using addition operation on numbers.
Here's my code:
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode a, ListNode b) {
if(a==null || b==null){
return null;
}
String num1 = "";
String num2 = "";
ListNode temp1 = a;
ListNode temp2 = b;
while(temp1!=null){
num1 = num1+Integer.toString(temp1.val);
temp1 = temp1.next;
}
new StringBuilder(num1).reverse().toString();
double value1 = Double.parseDouble(num1);
while(temp2!=null){
num2 = num2+Integer.toString(temp2.val);
temp2 = temp2.next;
}
new StringBuilder(num2).reverse().toString();
double value2 = Double.parseDouble(num2);
double result = value1+value2;
String res = String.format("%.0f",result);
ListNode first_node = new ListNode(Character.getNumericValue(res.charAt(0)));
ListNode ans = first_node;
for(int j=1;j<res.length();j++){
ListNode node = new ListNode(Character.getNumericValue(res.charAt(j)));
add(node,ans);
}
return ans;
}
public void add(ListNode node, ListNode ans){
ListNode temp;
temp = ans;
ans = node;
ans.next = temp;
}
}
My code has been giving wrong answers. Can anyone point out the errors?
Your approach is not correct and indirect.
You are trying to do big numbers arithmetics using floating point operations.
As a result - computing errors.
We have:
List<Integer> firstNumber;
List<Integer> secondNumber;
Lets assume firstNumber > secondNumber.
Try this alogrithm:
List<Integer> result = new ArrayList<>();
int i = 0;
int appendix = 0;
for (; i < secondNumber.size(); i++) {
int sum = firstNumber.get(i) + secondNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
for (; i < firstNumber.size(); i++) {
int sum = firstNumber.get(i) + appendix;
result.append(sum % 10);
appendix = sum / 10;
}
if (appendix != 0)
result.append(appendix);
return result;
Your add function looks incorrect. You will get you number in the reverse order than what is expected.
Also, your solution is missing the point of the question. Your approach will fail if you have a number with a lot of digits (even double has its limits ~ 2^1024 I think). A linked list representation allows for numbers even bigger.
The correct solution would just iterate through both the lists simultaneously with a carry digit while creating the solution list. If this is a question in an assignment or coding competition, your solution would be judged wrong.
Your add method is wrong, it doesn't build correctly the list. Here is how the final part of your method should look, without the add method:
for(int j=1;j<res.length();j++){
ans.next = new ListNode(Character.getNumericValue(res.charAt(j)));;
ans = ans.next;
}
return first_node;
In your approach, the variable ans is not updating. You can try this:
ans = add(node,ans);
and in your add method, change the method to return ListNode ans
Your approach is not straightforward and wouldn't give you expected results.
Here is a simple approach which wouldn't require much explanation as the addition is simple integer by integer.
Do note that i carry forward when the sum of two integers is greater than 9 else continue with the sum of next integers from both the list.
class Node {
private Object data;
private Node next;
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; }
public Node(final Object data, final Node next) {
this.data = data;
this.next = next;
}
#Override
public String toString() { return "Node:[Data=" + data + "]"; }
}
class SinglyLinkedList {
Node start;
public SinglyLinkedList() { start = null; }
public void addFront(final Object data) {
// create a reference to the start node with new data
Node node = new Node(data, start);
// assign our start to a new node
start = node;
}
public void addRear(final Object data) {
Node node = new Node(data, null);
Node current = start;
if (current != null) {
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(node);
} else {
addFront(data);
}
}
public void deleteNode(final Object data) {
Node previous = start;
if (previous == null) {
return;
}
Node current = previous.getNext();
if (previous != null && previous.getData().equals(data)) {
start = previous.getNext();
previous = current;
current = previous.getNext();
return;
}
while (current != null) {
if (current.getData().equals(data)) {
previous.setNext(current.getNext());
current = previous.getNext();
} else {
previous = previous.getNext();
current = previous.getNext();
}
}
}
public Object getFront() {
if (start != null) {
return start.getData();
} else {
return null;
}
}
public void print() {
Node current = start;
if (current == null) {
System.out.println("SingleLinkedList is Empty");
}
while (current != null) {
System.out.print(current);
current = current.getNext();
if (current != null) {
System.out.print(", ");
}
}
}
public int size() {
int size = 0;
Node current = start;
while (current != null) {
current = current.getNext();
size++;
}
return size;
}
public Node getStart() {
return this.start;
}
public Node getRear() {
Node current = start;
Node previous = current;
while (current != null) {
previous = current;
current = current.getNext();
}
return previous;
}
}
public class AddNumbersInSinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList listOne = new SinglyLinkedList();
SinglyLinkedList listTwo = new SinglyLinkedList();
listOne.addFront(5);
listOne.addFront(1);
listOne.addFront(3);
listOne.print();
System.out.println();
listTwo.addFront(2);
listTwo.addFront(9);
listTwo.addFront(5);
listTwo.print();
SinglyLinkedList listThree = add(listOne, listTwo);
System.out.println();
listThree.print();
}
private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
SinglyLinkedList result = new SinglyLinkedList();
Node startOne = listOne.getStart();
Node startTwo = listTwo.getStart();
int carry = 0;
while (startOne != null || startTwo != null) {
int one = 0;
int two = 0;
if (startOne != null) {
one = (Integer) startOne.getData();
startOne = startOne.getNext();
}
if (startTwo != null) {
two = (Integer) startTwo.getData();
startTwo = startTwo.getNext();
}
int sum = carry + one + two;
carry = 0;
if (sum > 9) {
carry = sum / 10;
result.addRear(sum % 10);
} else {
result.addRear(sum);
}
}
return result;
}
}
Sample Run
Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]
I am trying this program but i am not able to achieve deletion. The execution is going into infinite loop. Also, i am not sure if i am forming linked list properly.
What am i missing in the following program:
public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;
private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}
public static void main(String[] args) {
int k = 3;
Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);
second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;
Node result = removalKthNode(list, k);
int j = 1;
while(result.next!=null){
System.out.println(j+": "+result.item);
}
}
private static Node removalKthNode(Node first, int k) {
Node temp = first;
for(int i=1; i < k; i++) {
temp = temp.next;
}
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return temp;
}
}
THANKS A TON for answer and comments.. the working program is listed below:
public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;
private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}
public static void main(String[] args) {
int k = 3;
Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);
second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;
Node result = removalKthNode(list, k);
int j = 1;
while(result != null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}
}
private static Node removalKthNode(Node first, int k) {
Node temp = first;
for(int i=1; i < k; i++) {
temp = temp.next;
}
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return first;
}
}
The output is:
1: First
2: Second
3: Fourth
This looks like the culprit.
while(result.next!=null){
System.out.println(j+": "+result.item);
}
you are not progressing forward in the linked list.
I'm not exactly sure what you intended, but you may want to write as follows to avoid infinite loop...
while(result !=null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}
But again if you want to print whole linked list, you should not initialise result with the value returned from removalKthNode function. You should start from first.
Hope this makes sense.
You have several issues in your code:
1) The removalKthNode method should return the 1st element in the list to make your code print meaningful results (or you'll have to navigate to the 1st element again to output the remaining list.
2) The while loop which prints your list is wrong in two places.
a) You do not increment j, so you always put the same position for the items.
b) You do not really iterate through that list, meaning you do not reassign your variable result.
Try something like this:
int j = 1;
while (result != null) {
System.out.println(j++ + ": " + result.item);
result = result.next;
}
The code
Node result = removalKthNode(list, k);
now result = Third
and you have while loop as while(result.next!=null) which is always be in the Third element so it's going for infinite loop. Change the result as below
while(result!=null){
System.out.println(j+": "+result.item);
result = result.next;
}
Try this : Might help you to accompalish the Task:
package com.amazon;
class Linkedlist{
Node head;
public Linkedlist() {
head = null;
}
public Node addNode(int data){
Node newNode = new Node(data);
if(head==null) head = newNode;
else{
Node current = head;
while(current.next!=null){
current = current.next;
}
current.next = newNode;
}
return newNode;
}
}
class Node
{
Node next;
int data;
Node(int d)
{
data = d;
next = null;
}
}
public class DeleteEveryKthNodes {
void modifyList(Node head,int k){
Node current = head;
Node previous = null;
Node newHead = null;
if(current==null)return;
int count;
while (current != null) {
for (count = 1; count < k && current != null; count++) {
previous = current;
current = current.next; // 1--2--3--4--5
}
if (current != null) {
Node temp = current;
previous.next = current.next;
// current = null;
temp = null;
current = current.next;
}
}
current = head;
while(current!=null){
System.out.print(" "+current.data);
current = current.next;
}
}
public static void main(String args[]) {
Linkedlist list = new Linkedlist();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
new DeleteEveryKthNodes().modifyList(list.head, 2);
//list.head.next.next.next.next = new Node(1);
}
}
Simple Java Script for circular - n=5 and k=3, it will delete every 3 element in circular list.
public class TEST {
public static int killed_position(int[] newarr,int n,int a,int p) {
int iteration=0;
while(true) {
if(newarr[p-1] != 0) {
iteration++;
if(iteration>a-1) {
break;
}
}
p++;
if(p>n) {
p=1;
}
}
return p;
}
public static int next_position(int[] newarr,int n,int a,int p) {
int iteration=0;
while(iteration<1) {
if(newarr[p-1] != 0) {
iteration++;
}
else {
p++;
if(p>n) {
p=1;
}
}
}
System.out.println("NEXT START ->" + p);
return p;
}
public static void main(String[] args) {
int n=5;
int k=3;
int newarr[] = new int[n];
int a=1;
for(int i=0;i<n;i++) {
newarr[i]=i+1;
}
for(int i=1;i<n;i++) {
System.out.println("START -> " + a);
a=killed_position(newarr, n,k,a);
newarr[a-1]=0;
System.out.println("KILLED -> " + a);
a=next_position(newarr, n,k,a);
System.out.println("---------------------");
}
System.out.println("POSITION FINAL MAN -> " + a);
System.out.println("POSITION FINAL MAN NAME -> " + a);
for(int i=0;i<n;i++) {
System.out.print(newarr[i]);
}
}
}