function
Node(value) {
this
.value = value;
this
.next =
null
;
}
let head =
null
;
function
addnode(value) {
let node =
new
Node(value);
if
(head ===
null
) {
head = node;
}
else
{
let current = head;
while
(current.next) {
current = current.next;
}
current.next = node;
}
}
function
traverse() {
let current = head;
while
(current) {
process.stdout.write(current.value +
" "
);
current = current.next;
}
}
function
insertatbegin(value) {
let node =
new
Node(value);
node.next = head;
head = node;
}
function
insertatend(value) {
let node =
new
Node(value);
if
(head ===
null
) {
head = node;
}
else
{
let current = head;
while
(current.next) {
current = current.next;
}
current.next = node;
}
}
function
insertatpos(value, position) {
let node =
new
Node(value);
if
(head ===
null
) {
head = node;
}
else
{
let current = head;
let count = 1;
while
(count < position && current.next) {
current = current.next;
count++;
}
node.next = current.next;
current.next = node;
}
}
function
delatbegin() {
if
(head !==
null
) {
head = head.next;
}
}
function
delatend() {
if
(head ===
null
) {
return
;
}
if
(head.next ===
null
) {
head =
null
;
return
;
}
let current = head;
while
(current.next.next) {
current = current.next;
}
current.next =
null
;
}
function
delatpos(position) {
if
(head ===
null
) {
return
;
}
let current = head;
if
(position === 1) {
head = current.next;
return
;
}
let count = 1;
let prev =
null
;
while
(count < position && current.next) {
prev = current;
current = current.next;
count++;
}
if
(current ===
null
) {
return
;
}
prev.next = current.next;
}
addnode(2);
addnode(4);
addnode(9);
addnode(1);
addnode(21);
addnode(22);
process.stdout.write(
"Linked List: "
);
traverse();
process.stdout.write(
"\n"
);
insertatbegin(1);
process.stdout.write(
"Linked List after inserting 1 at beginning: "
);
traverse();
process.stdout.write(
"\n"
);
insertatend(0);
process.stdout.write(
"Linked List after inserting 0 at end: "
);
traverse();
process.stdout.write(
"\n"
);
insertatpos(44, 3);
process.stdout.write(
"Linked List after inserting 44 after 3rd Node: "
);
traverse();
process.stdout.write(
"\n"
);
delatbegin();
process.stdout.write(
"Linked List after deleting node at beginning: "
);
traverse();
process.stdout.write(
"\n"
);
delatend();
process.stdout.write(
"Linked List after deleting node at end: "
);
traverse();
process.stdout.write(
"\n"
);
delatpos(5);
process.stdout.write(
"Linked List after deleting node at position 5: "
);
traverse();
process.stdout.write(
"\n"
);