Skip to content

Instantly share code, notes, and snippets.

@iAmWillShepherd
Created December 4, 2017 02:07
Show Gist options
  • Save iAmWillShepherd/9a9a3e662d90bfdbea453b2ff15c850c to your computer and use it in GitHub Desktop.
Save iAmWillShepherd/9a9a3e662d90bfdbea453b2ff15c850c to your computer and use it in GitHub Desktop.
interface INode {
data: number;
next: INode | null;
}
class LinkedList {
private _head: INode | null;
public insert(value: number, index: number) {}
public prepend(value: number) {
const node = this.createNode(value);
if (!this._head) {
this._head = node;
} else {
node.next = this._head;
this._head = node;
}
}
public append(value: number) {
const newNode = this.createNode(value);
let currNode = this._head;
if (this._head === null) {
this._head = newNode;
} else {
while (currNode.next) {
currNode = currNode.next;
}
currNode.next = newNode;
}
}
public toString() {
let result: string = "";
let node: INode | null = this._head;
while (node) {
result += `${node.data} -> `;
node = node.next;
}
result += "nil";
return result;
}
public recToString() {
return this.recToStringHelper(this._head);
}
private recToStringHelper(node: INode | null, str: string = "") {
if (!node) return (str += "nil");
return this.recToStringHelper(node.next, (str += `${node.data} -> `));
}
private createNode(value: number) {
return {
data: value,
next: null
};
}
}
var list = new LinkedList();
list.prepend(5);
list.prepend(10);
list.prepend(15);
list.append(30);
list.recToString(); /*?*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment