Skip to content

Instantly share code, notes, and snippets.

@kshitijvarshne1
Created February 8, 2021 06:17
Show Gist options
  • Save kshitijvarshne1/cad5b1a730d39022f77d02cb38265548 to your computer and use it in GitHub Desktop.
Save kshitijvarshne1/cad5b1a730d39022f77d02cb38265548 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();
}
}
/* 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;
//System.out.println(temp.data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment