How to insert a node in specific index [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
First of all pardon me if the way I'm asking is wrong, I'm new at programming and still need a lot of learning, here is my code
This is my Node class
public class Node
{
int value;
Node link;
void setValue(int a){
value = a;
}
int getValue(){
return value;
}
void setNode(Node i){
link = i;
}
Node getNode(){
return link;
}
}
And this one my NodeContainer class
public class NodeContainer
{
Node tail;
Node head;
void setHead(int i){
Node a = new Node();
a.setValue(i);
head = a;
tail = head;
}
Node getHead(){
return head;
}
void addNode(int i){
Node a = new Node();
a.setValue(i);
tail.setNode(a);
tail = a;
}
void addNode(int i,int index){
Node a = new Node();
a.setValue(i);
int c = 1;
Node temp = head;
Node first = head;
while(head!=null){
head = head.getNode();
if(c==index-1){
a.setNode(head.getNode());
temp = head;
temp.setNode(a);
}
c++;
}
head = first;
head.setNode(temp);
}
int count(){
int c = 1;
boolean have = true;
if(head!=null){
while(head.getNode()!=null){
c++;
head = head.getNode();
}
return c;
}
else{
have = false;
return 0;}
}
}
i just cant think a way to insert a node in spesific index, i tried it on addNode method have tried so many ways i can think of but it cant work, thanks in advance

Comments:
You do not need to keep track of the tail (necessarily) I see you are new to linked lists, so perhaps try to master the basics before adding extra features.
Also, try adding some white space in your code, it makes it easier to read.
I heavily commented the section that covers inserting at a specified index. put all these files in the same folder, the compile it. You should get the output that follows:
Output:
0 1 2 3 4 5 6 7 8 9
inserting -1 at position 5
0 1 2 3 4 -1 5 6 7 8 9
Main class:
class test {
public static void main(String[] args) {
NodeContainer linkedList = new NodeContainer();
for (int i = 0; i < 10; i++) {
linkedList.addNode(i);
}
display(linkedList.head);
// NOTE - indexes start at 0, not 1
System.out.println("inserting -1 at position 5");
linkedList.addNode(-1, 5);
display(linkedList.head);
}
public static void display(Node node) {
while (node != null) {
System.out.print(node.value + " ");
node = node.link;
}
System.out.println();
}
}
Node Container class:
public class NodeContainer {
public Node head;
public int size;
public NodeContainer() {
size = 0;
head = null;
}
public void addNode(int i) {
Node node = new Node(i);
if (head == null) {
head = node;
} else {
Node temp;
temp = head;
while (temp.link != null) {
temp = temp.link;
}
temp.link = node;
}
size++;
}
public void addNode(int i, int index) {
Node node;
Node temp;
int count;
// If we want to insert
// into the front of the list
if (index == 0) {
// User a constructor instead of
// making a new node every time,
// then typing set value
node = new Node(i);
node.link = head;
head = node;
// If the index is within the linkedlist
} else if (index > 0 && index < size) {
count = 0;
temp = head;
// Keep looking until the index prior to
// the one we want to insert at
while(temp.link != null && count < size) {
// Once we find it, break out the loop
if (count == index-1) {
break;
}
// Keep traversing the list
temp = temp.link;
// increment counter
count++;
}
// Instantiate the node
node = new Node(i);
// Point this node's link to
// the n-1th node's link
node.link = temp.link;
// Set n-1th node's next to this
// node (effectively putting it
// in position n)
temp.link = node;
// Otherwise don't do anything
} else {
;
}
}
}
Node class:
public class Node {
public int value;
public Node link;
// User a constructor
public Node(int i) {
value = i;
link = null;
}
public void setValue(int a) {
value = a;
}
public int getValue() {
return value;
}
public void setNode(Node i) {
link = i;
}
public Node getNode() {
return link;
}
}

I have updated your original code snippet to be like this :
public class Node
{
int value;
Node next;
void setValue(int value){
this.value = value;
}
int getValue(){
return this.value;
}
void setNext(Node next){
this.next = next;
}
Node getNext(){
return this.next;
}
}
public class NodeContainer {
Node tail;
Node head;
void setHead(int i) {
Node a = newNode(i);
head = a;
tail = a;
}
private Node newNode(int value) {
Node node = new Node();
node.setValue(i);
return node;
}
void addNode(int i) {
Node a = newNode(i);
Node tmp = this.head;
while(tmp.getNext() != null){
tmp = tmp.getNext();
}
tmp.setNext(a);
tail = a;
}
void addNode(int value, int index) {
//TODO : add check on head
Node a = newNode(value);
Node tmp = this.head;
int i = 0;
while(tmp.getNext()!=null && i < index) {
tmp = tmp.getNext();
i++;
}
//TODO : add check on tmp
Node next = tmp.getNext();
tmp.setNext(a);
a.setNext(next);
}
int count() {
//...
}
}

Related

trouble implementing a linked list in java

I tried to implement a linked list in java using the code below:
class Linkedlist<T>{
private node head, tail;
public Linkedlist(){
head = new node(null);
tail = head;
}
public boolean insert(T value){
if(head.getValue() == null){
this.head.setValue(value);
head.setNext(null);
return true;
}
node insertNode = new node(value);
tail.setNext(insertNode);
tail = insertNode;
return true;
}
public boolean insert(T value, int index) {
if ( sizeOfList() == index + 1 ) return false;
node temp = this.head.getNext();
node prvtmp = this.head;
for (int i = 0; i <= index; i++) {
temp = temp.getNext();
prvtmp = temp;
System.out.println("for loop");
}
node insertNode = new node(value);
System.out.println("node created");
prvtmp.setNext(insertNode);
insertNode.setNext(temp);
System.out.println("temps");
return true;
}
public int sizeOfList(){
int size = 0;
node temp = this.head;
while(temp.getNext() != null){
temp = temp.getNext();
size++;
}
return size;
}
public String[] rtrnList(){
node temp = this.head;
int listSize = sizeOfList();
String[] resualt = new String[listSize + 1];
for (int i = 0;i <= listSize;i++){
resualt[i] = String.valueOf(temp.getValue());
temp = temp.getNext();
}
return resualt;
}
}
Class node:
public class node<T> {
private T value;
private node next;
public node(T value){
this.value = value;
this.next = null;
}
public void setValue(T value) {
this.value = value;
}
public void setNext(node next) {
this.next = next;
}
public T getValue() {
return value;
}
public node getNext() {
return next;
}
}
When I try to run the insert method with one argument it works fine, but when I run it with two arguments:
import java.util.Arrays;
public class main {
public static void main(String[] args){
Linkedlist list = new Linkedlist();
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(11, 3);
System.out.println(Arrays.toString(list.rtrnList()));
System.out.println("finished");
}
}
The program doesn't reach the line that prints finished, but if we delete the line: list.insert(11, 3);
Then the program works just fine.
output:
for loop
for loop
for loop
for loop
node created
finish insert
The problems is inside the for loop of your insert(T value, int index) method when you are updating the value of prvtm and temp. In your code you are first setting the value of temp to temp.getnext() and as the temp is already changed setting prvtmp to temp creating a loop which is why when you are trying to print the list it's getting into an infinite loop while calculating the size of the list.
Just put the prvtmp = temp line before temp = temp.getNext() like following code snippet. This will solve the problem.
public boolean insert(T value, int index) { // 2 2 2 2 2 2
if ( sizeOfList() == index + 1 ) return false;
node temp = this.head.getNext();
node prvtmp = this.head;
for (int i = 0; i <= index; i++) {
prvtmp = temp;
temp = temp.getNext();
System.out.println("for loop");
}
node insertNode = new node(value);
System.out.println("node created");
prvtmp.setNext(insertNode);
insertNode.setNext(temp);
System.out.println("temps");
return true;
}
Also if you are trying to insert in the given index update the condition of the for loop from:
i <= index to i < index - 1
Happy coding!
while inserting there is a cyclic refrence made , you can use this code for above purpose
public boolean insert(T value, int index) {
if(index > sizeOfList())
{
return false;
}
else if(index == sizeOfList())
{
if(insert(value))
return true;
else
return false;
}
else
{
node previous = this.head;
for (int i = 1; i <= index; i++) {
if(i==index-1)
{
node newnode = new node(value);
newnode.setNext(previous.getNext());
previous.setNext(newnode);
break;
}
previous = previous.getNext();
}
}
return true;
}
Output
[2, 2, 11, 2, 2, 2, 2]

Infinite loop is occurring. How to fix it?

import java.util.Scanner;
public class reverse {
private Node head;
private int listCount;
public reverse() {
head = new Node(null);
listCount = 0;
}
public static void main(String args[]) {
reverse obj = new reverse();
Scanner sc = new Scanner(System.in);
int n, i, x;
System.out.println("How many no.s?");
n = sc.nextInt();
for (i = 1; i <= n; i++) {
System.out.println("enter the no.");
x = sc.nextInt();
obj.add(x);
}
Node newhead = obj.method1(obj.head);
obj.display(newhead);
}
public void add(Object data) {
Node temp = new Node(data);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
listCount++;
}
public void display(Node newhead) {
Node current = newhead;
//System.out.println(current.getNext().getNext().getNext().getNext().getNext().getData());
while (current != null) {
System.out.print(current.getData() + " " +);
current = current.getNext();
}
}
public Node method1(Node head) {
if (head == null) {
return head;
}
Node first = head.getNext();
Node second = first.getNext();
first.setNext(head);
head = null;
if (second == null)
return head;
Node current = second;
Node prev = first;
while (current != null) {
Node upcoming = current.getNext();
current.setNext(prev);
prev = current;
current = upcoming;
//System.out.println(prev.getData());
//System.out.println(current.getData());
}
head = prev;
return head;
}
private 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;
}
}
}
My while statement is not working properly.
Initial value of newhead.getData() is 5. The comment part in my code is also giving value as null which is correct, but after that there is some error in my while loop.
I have written code for reversing a linked list.
display() method is to print all the list elements.
Input from user of linked list is:
1 2 3 4 5
Output should be:
5 4 3 2 1
But my output is:
null 1 null 1 null 1............occurring infinite times.
you have a problem when you a filling your data .
all nods have the same reference
try to print your list
for(int i=;i;list.size();i++)
System.out.print(list.getObjectAtIndex(i).getData);

Bubble Sort Manually a Linked List in Java

This is my first question here.
I am trying to manually sort a linked list of integers in java and I can not figure out what is wrong with my code. Any suggestions? I don't get any error, however I still have my output unordered. I tried a few different ways, but nothing worked. I appreciate if anyone can help me with that.
public class Node {
int data;
Node nextNode;
public Node(int data) {
this.data = data;
this.nextNode = null;
}
public int getData() {
return this.data;
}
} // Node class
public class DataLinkedList implements DataInterface {
private Node head;
private int size;
public DataLinkedList(){
this.head = null;
this.size = 0;
}
public void add(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
} else {
Node currentNode = head;
while(currentNode.nextNode != null) {
currentNode = currentNode.nextNode;
}
currentNode.nextNode = node;
}
size++;
}
public void sort() {
if (size > 1) {
for (int i = 0; i < size; i++ ) {
Node currentNode = head;
Node next = head.nextNode;
for (int j = 0; j < size - 1; j++) {
if (currentNode.data > next.data) {
Node temp = currentNode;
currentNode = next;
next = temp;
}
currentNode = next;
next = next.nextNode;
}
}
}
}
public int listSize() {
return size;
}
public void printData() {
Node currentNode = head;
while(currentNode != null) {
int data = currentNode.getData();
System.out.println(data);
currentNode = currentNode.nextNode;
}
}
public boolean isEmpty() {
return size == 0;
}
} // DataInterface class
public class DataApp {
public static void main (String[]args) {
DataLinkedList dll = new DataLinkedList();
dll.add(8);
dll.add(7);
dll.add(6);
dll.add(4);
dll.add(3);
dll.add(1);
dll.sort();
dll.printData();
System.out.println(dll.listSize());
}
} // DataApp class
The problem, as expected, comes in method sort():
public void sort() {
if (size > 1) {
for (int i = 0; i < size; i++ ) {
Node currentNode = head;
Node next = head.nextNode;
for (int j = 0; j < size - 1; j++) {
if (currentNode.data > next.data) {
Node temp = currentNode;
currentNode = next;
next = temp;
}
currentNode = next;
next = next.nextNode;
}
}
}
}
A minor problem is just do always execute the bubble sort n*n times. It is actually better check whether there was a change between any pair in the list. If it was, then there is the need to run again all over the list; if not, there isn't. Think of the marginal case in which a list of 100 elements is already sorted when sort() is called. This means that nodes in the list would be run over for 10000 times, even when there is actually nothing to do!
The main problem, though, is that you are exchanging pointers to the nodes in your list.
if (currentNode.data > next.data) {
Node temp = currentNode;
currentNode = next;
next = temp;
}
If you translate currentNode by v[i] and next by v[i - 1], as if you were sorting an array, that would do. However, you are just changing pointers that you use to run over the list, without effect in the list itself. The best solution (well, provided you are going to use BubbleSort, which is always the worst solution) would be to exchange the data inside the nodes.
if (currentNode.data > next.data) {
int temp = currentNode.data;
currentNode.data = next.data;
next.data = temp;
}
However, for a matter of illustration of the concept, I'm going to propose changing the links among nodes. These pointers are the ones which actually mark the sorting in the list. I'm talking about the nextNode attribute in the Node class.
Enough chat, here it is:
public void sort() {
if (size > 1) {
boolean wasChanged;
do {
Node current = head;
Node previous = null;
Node next = head.nextNode;
wasChanged = false;
while ( next != null ) {
if (current.data > next.data) {
/*
// This is just a literal translation
// of bubble sort in an array
Node temp = currentNode;
currentNode = next;
next = temp;*/
wasChanged = true;
if ( previous != null ) {
Node sig = next.nextNode;
previous.nextNode = next;
next.nextNode = current;
current.nextNode = sig;
} else {
Node sig = next.nextNode;
head = next;
next.nextNode = current;
current.nextNode = sig;
}
previous = next;
next = current.nextNode;
} else {
previous = current;
current = next;
next = next.nextNode;
}
}
} while( wasChanged );
}
}
The explanation for a "double" code managing the node exchange is that, since you have to change the links among nodes, and this is just a single linked list, then you have to keep track of the previous node (you don't have a header node, either), which the first time is head.
if ( previous != null ) {
Node sig = next.nextNode;
previous.nextNode = next;
next.nextNode = current;
current.nextNode = sig;
} else {
Node sig = next.nextNode;
head = next;
next.nextNode = current;
current.nextNode = sig;
}
You can find the code in IdeOne, here: http://ideone.com/HW5zw7
Hope this helps.
You need to swap the data not just the nodes.
public void sort() {
if (size > 1) {
for (int i = 0; i < size; i++ ) {
Node currentNode = head;
Node next = head.nextNode;
for (int j = 0; j < size - 1; j++) {
if (currentNode.data > next.data) {
int temp = currentNode.data;
currentNode.data = next.data;
next.data = temp;
}
currentNode = next;
next = next.nextNode;
}
}
}
}
you can write this methode like this:
class Node {
int data = 0;
Node next;
public Node(int data) {
this.data = data;
}
}
public void sort() {
Node current = head;
while (current != null) {
Node second = current.next;
while (second != null) {
if (current.data > second.data) {
int tmp = current.data;
current.data = second.data;
second.data = tmp;
}
second = second.next;
}
current = current.next;
}
}

Reversing a singly linked list in java

I made a singly linked list from scratch in java. The code is as follows:
public class SingleLinkedList<Item>
{
private Node head;
private int size;
private class Node
{
Item data;
Node next;
public Node(Item data)
{
this.data = data;
this.next = null;
}
public Node(Item data, Node next)
{
this.data = data;
this.next = next;
}
//Getters and setters
public Item getData()
{
return data;
}
public void setData(Item data)
{
this.data = data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next = next;
}
}
public SingleLinkedList()
{
head = new Node(null);
size = 0;
}
public void add(Item data)
{
Node temp = new Node(data);
Node current = head;
while(current.getNext() != null)
{
current = current.getNext();
}
current.setNext(temp);
size++;
}
public void add(Item data, int index)
{
Node temp = new Node(data);
Node current = head;
for(int i=0; i<index && current.getNext() != null; i++)
{
current = current.getNext();
}
temp.setNext(current.getNext());
current.setNext(temp);
size++;
}
public Item get(int index)
{
if(index <= 0)
{
return null;
}
Node current = head;
for(int i=1; i<index; i++)
{
if(current.getNext() == null)
{
return null;
}
current = current.getNext();
}
return current.getData();
}
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());
size--;
return true;
}
public String toString()
{
Node current = head.getNext();
String output = "";
while(current != null)
{
output+=current.getData().toString()+" ";
current = current.getNext();
}
return output;
}
public int size()
{
return size;
}
public void reverse()
{
Node current = head;
Node prevNode = null;
Node nextNode;
while(current!=null)
{
nextNode = current.getNext();
current.setNext(prevNode);
prevNode = current;
current = nextNode;
System.out.println(prevNode.getData());
}
head = prevNode;
}
}
As you can see, I added the reverse function in the class only.
But when I tried actually using the class it gave NullPointerException after I tried to reverse it.
To check the functionality I used another class called TEST. The code is as follows:
public class TEST
{
public static void main(String[] args)
{
SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println(list.toString());
list.reverse();
System.out.println(list.toString());
}
}
The output is as follows:
1 2 3 4 5
null
1
2
3
4
5
Exception in thread "main" java.lang.NullPointerException
at SingleLinkedList.toString(SingleLinkedList.java:129)
at TEST.main(TEST.java:20)
I tried to print the value of prevNode to check whether its not taking values...but it is.
What to do?
Actually, your reverse method looks fine.
The problem is your toString() method.
When you create a new list, you create an initial element whose data is null.
Your toString method skips that first element, so it works fine as long as you don't reverse the list.
But when you reverse the list, that null element becomes the last element, and when you call output+=current.getData().toString()+" "; for that last element when current.getData() is null, you get NullPointerException.
You have several options :
Your reverse method can keep the initial null element first (i.e. reverse the rest of the list, but keep the head the same). This way toString can remain unchanged.
Eliminate the initial null element. Then your toString method doesn't have to skip anything.
Keeping the null element first :
public void reverse()
{
Node current = head.getNext();
Node prevNode = null;
Node nextNode;
while(current!=null)
{
nextNode = current.getNext();
current.setNext(prevNode);
prevNode = current;
current = nextNode;
System.out.println(prevNode.getData());
}
head.setNext(prevNode);
}
The problem is in your SingleLinkedList.java toString() method
Try below it is working fine
public String toString() {
Node current = head;
String output = "";
while (current != null) {
// output += current.getData().toString() + " ";
output += String.valueOf(current.getData()) + " ";
current = current.getNext();
}
return output;
}
while(current!=null)
This is your problem. When you hit the last node the 'next' node you get is actually null.
Try changing it to
while(current!=null&&current.getNext()!=null)
EDIT: Actually not sure that solution will work. Try putting a conditional at the end of your loop that says:
if(current.getNext()==null)
break;
EDIT (again :/):
ok sorry I wasn't thinking straight.
change that final if statement to:
if(current.getNext()==null){
current.setNext(prevNode);
break;
}
The actual nullpointer is in the toString. Here's what you do:
Change the while conditional to
while(current != null&&current.getData()!=null)
Because otherwise if current points to null then you get an exception.
That was exhausting.

Having some trouble using a Linked List and passing elements to the Node

In this specific instance, it takes into account two occasions. One where I'm trying to place a node in the beginning of the Linked List and one where I'm trying to place it in the middle or at the end. Here is my Node Class. If you look at my INSERT method, the part that is not working is:
Node newNode = new Node();
newNode.setExponent(element);
class Node {
private int coefficient;
private int exponent;
private Node link;
// Constructor: Node()
Node(int c, int e) {
// Sets coefficient to c, exponent to e, and link to null
coefficient = c;
exponent = e;
link = null;
}
// Inspectors: getCoefficient(), getExponent(), getLink()
public int getCoefficient() {
// Returns coefficient
return coefficient;
}
public int getExponent() {
// Returns exponent
return exponent;
}
public Node getLink() {
// Returns link
return link;
}
// Modifiers: setCoefficient(), setExponent(), setLink()
public void setCoefficient(int c) {
// Sets coefficient to c
coefficient = c;
}
public void setExponent(int e) {
// Sets exponent to e
exponent = e;
}
public void setLink(Node n) {
// Sets link to n
link = n;
}
}// Ends Node Class
Here is where I'm trying to insert to my Linked List along with some other methods in the class that should help give you an idea of how my code looks.
class List {
private Node head; // Points to first element of the list
private int count; // number of elements in the list
// Constructor:
List() {
// Sets head to null and count to zero
head = null;
count = 0;
}
// Inspectors:
// Returns the number of elements in the list
public int size() {
return count;
}
// Modifiers:
// Inserts element at index in the list. Returns true if successful
public boolean insert(int index, Node element) {
if (index < 0 || index > count)return false;
if (index == 0) {
Node newNode = new Node();
newNode.setExponent(element);
count++;
newNode.setLink(head);
head = newNode;
return true;
}
Node walker = head;
for (int i = 1; i < (index - 1); i++)
walker = walker.getLink();
Node newNode = new Node();
newNode.setExponent(element);
newNode.setLink(walker.getLink());
walker.setLink(newNode);
count++;
return true;
}
Try this:
Assumption: You are trying to insert a Node element into the index of LinkedList
Your insert method with modification.
public boolean insert(int index, Node element) {
//if (index < 0 || index > count)
if (index < 0 || index > count + 1) return false;
if(head == null) {
head = element;
return true;
}
if (index == 0) {
//Node newNode = new Node();
//newNode.setExponent(element);
count++;
element.setLink(head);
//newNode.setLink(head);
head = element;
//head = newNode;
return true;
}
Node walker = head;
//for (int i = 0; i < (index - 1); i++)
for (int i = 1; i < index; i++) {
walker = walker.getLink();
}
//Node newNode = new Node();
//newNode.setExponent(element);
element.setLink(walker.getLink());
//newNode.setLink(walker.getLink());
//walker.setLink(newNode);
walker.setLink(element);
count++;
return true;
}
Sample Test Case:
print method:
void print() {
Node travel = head;
while(travel!= null) {
System.out.println(travel.getExponent() + " " + travel.getCoefficient());
travel = travel.getLink();
}
}
Main method:
public static void main(String args[]) {
Node n1 = new Node(1,2);
List l = new List();
l.insert(0,n1);
Node n2 = new Node(3,2);
l.insert(1,n2);
Node n3 = new Node(4,5);
l.insert(0,n3);
l.print();
}

Categories