Skip to content

Instantly share code, notes, and snippets.

@bvsatyaram
Created November 8, 2016 11:35
Show Gist options
  • Save bvsatyaram/864dc235d965fa7a48f9008b2f415758 to your computer and use it in GitHub Desktop.
Save bvsatyaram/864dc235d965fa7a48f9008b2f415758 to your computer and use it in GitHub Desktop.
LinkedList.ts
import LinkedListNode from './linkedListNode';
export default class LinkedList {
private headSentinel;
constructor() {
this.headSentinel = new LinkedListNode(null);
}
head() {
return this.headSentinel.next;
}
find(index: number) {
if (index == -1) {
return this.headSentinel;
}
let ele = this.head();
for (let i = 0; i < index; i ++) {
ele = ele.next;
}
return ele;
}
insert(index: number, node: LinkedListNode) {
let preEle = this.find(index - 1);
let postEle = this.find(index);
node.next = postEle;
preEle.next = node;
}
delete(index: number) {
let preEle = this.find(index - 1);
let eleToDel = preEle.next;
let postEle = eleToDel.next;
preEle.next = postEle;
eleToDel.next = null;
}
print() {
let ele = this.head();
while (ele !== undefined) {
console.log(ele.value);
ele = ele.next;
}
}
}
import LinkedListNode from "./linkedListNode";
import LinkedList from "./linkedList";
let ll = new LinkedList;
let n1 = new LinkedListNode(1);
ll.insert(0, n1);
let n2 = new LinkedListNode(2);
ll.insert(0, n2);
let n3 = new LinkedListNode(3);
ll.insert(0, n3);
let n4 = new LinkedListNode(4);
ll.insert(1, n4);
ll.print();
ll.delete(1);
ll.print();
export default class LinkedListNode {
public next: LinkedListNode;
constructor(public value: any) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment