Skip to content

Instantly share code, notes, and snippets.

@kshitijvarshne1
Created February 8, 2021 12:04
Show Gist options
  • Save kshitijvarshne1/65b654ad82f4dcdd674507d9acfba2f3 to your computer and use it in GitHub Desktop.
Save kshitijvarshne1/65b654ad82f4dcdd674507d9acfba2f3 to your computer and use it in GitHub Desktop.
/* Created by IntelliJ IDEA.
* Author: Kshitij Varshney (kshitijvarshne1)
* Date: 08-Feb-21
* Time: 11:00 AM
* File: Execution.java
*/
package feb08_21_NK.LinkedList;
public class Execution {
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
for (int i = 0; i < 5; i++) {
list.insertAtBegin(new Node(i));
}
// list.printSinglyLinkedList();
Node n1 = new Node(1000);
list.insertAtEnd(n1);
//list.printSinglyLinkedList();
n1.data= 44;
list.insertAtBegin(n1);
//list.insertAtEnd(n1);
list.printSinglyLinkedList();
}
}
/* Created by IntelliJ IDEA.
* Author: Kshitij Varshney (kshitijvarshne1)
* Date: 08-Feb-21
* Time: 10:55 AM
* File: Node.java
*/
package feb08_21_NK.LinkedList;
public class Node {
int data;
Node next; // self reference structure
public Node(int d) {
data = d;
next = null;
}
}
/* Created by IntelliJ IDEA.
* Author: Kshitij Varshney (kshitijvarshne1)
* Date: 08-Feb-21
* Time: 10:57 AM
* File: SinglyLinkedList.java
*/
package feb08_21_NK.LinkedList;
public class SinglyLinkedList {
Node head;
public SinglyLinkedList() {
head = null;
}
public void insertAtBegin(Node newNode) {
newNode.next = head;
head = newNode;
}
public void printSinglyLinkedList() {
Node temp = head;
if (temp == null) {
System.out.println("No data member");
} else {
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println();
}
}
public void insertAtEnd(Node newNode) {
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
return;
}
}
@neer2808
Copy link

neer2808 commented Feb 8, 2021

The problem with is code is that when you insert the n1 at the last the value is 44 and next is null for this node

but when you insert the same record at the beginning then you modify the value of the next

this is the reason it produce infinity

and there is not loop termination condition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment