added singly linked list in java and javascript (#53)

* added singly linked list in java

* added commnets

* addded singly linked list in javascript

* Rename SinglyLinkedLIst.java to singly-linked-list.java
pull/57/head^2
Visrut 2021-02-02 21:32:08 +05:30 committed by GitHub
parent 1e5db415bf
commit 445a57d57b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,64 @@
class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
public class SinglyLinkedList<T> {
Node<T> head;
SinglyLinkedList() {
this.head = null;
}
void insertAtHead(T data) {
Node<T> newNode = new Node<T>(data);
if(this.head == null) {
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
}
T removeAtHead() {
// check for underflow
if(this.head == null) {
System.out.println("Underflow");
System.exit(1);
}
// store data for return
T data = this.head.data;
this.head = this.head.next;
return data;
}
void printList() {
// if head is null then list is empty
if(this.head == null) {
System.out.println("List is Empty");
} else {
// take itr same as head reference and loop through it until it became null
Node<T> itr = this.head;
while(itr != null) {
System.out.print(itr.data + " ");
itr = itr.next;
}
System.out.println("");
}
}
// Test Code
public static void main(String... args) {
SinglyLinkedList<String> l = new SinglyLinkedList<String>();
l.insertAtHead("abc");
l.insertAtHead("pqr");
l.insertAtHead("xyz");
l.removeAtHead();
l.printList();
}
}

View File

@ -0,0 +1,55 @@
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
}
insertAtHead(data) {
let newNode = new Node(data);
if(this.head == null) {
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
}
removeAtHead() {
// check for underflow
if(this.head == null) {
console.log("Underflow");
return;
}
// store head's reference data value in local data variable
let data = this.head.data;
this.head = this.head.next;
return data;
}
printList() {
// if head is null then list is empty
if(this.head == null) {
console.log("List is Empty");
} else {
// iterate through list until itr is not null
let itr = this.head;
while(itr != null) {
console.log(itr.data);
itr = itr.next;
}
}
}
}
let l = new SinglyLinkedList();
l.insertAtHead(1);
l.insertAtHead('xyz');
l.insertAtHead(1.1);
l.removeAtHead();
l.printList()