Singly Linked List Demo
HTML
<div>
<h4>
Linked List Operation Demo
</h4>
<div class="line">
<div class="Insert">
<input id="input-field" name='insert' placeholder='Enter element value'>
<button onclick="perform('insert')">
Insert
</button>
<button onclick="perform('delete')">
Delete
</button>
<button onclick="perform('search')">
Search
</button>
</div>
<div class="line">
</div>
</div>
<div class="seperate-line"></div>
<div class="result line">
<div id="current-status" class="line"> </div>
<div id="current-size" class="line"></div>
<div id="search-result"></div>
<div id="list-look" class="line"></div>
</div>
</div>
CSS
html,
* {
font-family: Arial;
font-size: 0.9rem;
}
button {
padding: 0.5rem;
background: #2fb1cc;
color: white;
border: none;
}
button:hover {
cursor: pointer;
}
#input-field,
#search {
padding: 0.4rem;
min-width: 50%;
}
.line {
margin-top: 0.5rem;
}
.seperate-line {
height: 1px;
background: #dad5d5;
margin: 1rem 0;
width: 100%;
}
#current-status {
color: green;
}
JavaScript
function Node(value) {
this.value = value;
this.next = undefined;
}
function SLinkedList() {
var head = undefined;
var length = 0;
return {
insert: function(item) {
console.log("the value of item", item);
if (!item) return;
var node = new Node(item);
if (head) {
node.next = head;
}
head = node;
length++;
},
delete: function(value) {
var curr = head;
if (head.value === value) {
head = head.next;
return;
}
while (curr) {
if (curr.next) {
var next = curr.next;
if (next.value === value) {
curr.next = next.next;
length--;
break;
}
}
curr = curr.next;
}
},
search: function(value) {
var curr = head;
var found = undefined;
while (curr) {
if (curr.value === value) {
found = curr;
break;
}
curr = curr.next;
}
return found;
},
size: function() {
return length;
},
print: function() {
var result = [];
var curr = head;
while (curr) {
result.push(curr.value);
curr = curr.next;
}
return result;
}
}
}
var demoLinkedList = new SLinkedList();
function perform(type) {
var status = document.getElementById('current-status');
status.innerHTML = 'Status: Processing...';
var input = document.getElementById('input-field');
if (input) {
var value = input.value;
var result = demoLinkedList[type](value);
input.value = "";
if (type === 'search') {
printSearch(result);
}
}
printDetails();
printStructure();
status.innerHTML = 'Status: Completed.'
}
function printSearch(node) {
var divDisplay = document.getElementById('search-result');
var result = "Search result: Not existed.";
if (node) {
result = 'Search result: ' + node.value;
if (node.next) {
...