203.移除链表元素
707.设计链表
206.反转链表
var removeElements = function(head, val) {
const dummyHead = new ListNode(-1, head);
let p0 = dummyHead, p1 = head;
while(p1) {
if (p1.val === val) {
const next = p1.next;
p1.next = null;
p1 = next;
p0.next = p1;
} else {
p0 = p0.next;
p1 = p1.next;
}
}
return dummyHead.next;
};
var ListNode = function(val, next) {
this.next = next ? next : null;
this.val = !!val ? val : 0;
}
var MyLinkedList = function() {
this.dummyHead = new ListNode(-1, null);
this.listLen = 0;
};
MyLinkedList.prototype.get = function(index) {
if (index < 0 || index >= this.listLen) return -1;
let p = this.dummyHead;
for (let i=0; i<=index; i++) {
p = p.next;
}
return p.val;
};
MyLinkedList.prototype.addAtHead = function(val) {
const newNode = new ListNode(val);
const currHead = this.dummyHead.next;
this.dummyHead.next = newNode;
newNode.next = currHead;
this.listLen += 1;
};
MyLinkedList.prototype.addAtTail = function(val) {
const newNode = new ListNode(val);
let tail = this.dummyHead;
while (tail.next) {
tail = tail.next;
}
tail.next = newNode;
this.listLen += 1;
};
MyLinkedList.prototype.addAtIndex = function(index, val) {
if (index > this.listLen) return;
if (index === 0) {
return this.addAtHead(val);
}
if (index === this.listLen) {
return this.addAtTail(val);
}
const newNode = new ListNode(val);
let p = this.dummyHead;
for (let i=0; i<index; i++) {
p = p.next;
}
const nextNode = p.next;
p.next = newNode;
newNode.next = nextNode;
this.listLen += 1;
};
MyLinkedList.prototype.deleteAtIndex = function(index) {
if (index < 0 || index >= this.listLen) return;
let p = this.dummyHead;
for (let i=0; i<index; i++) {
p = p.next;
}
const newNext = p.next.next;
p.next = null;
p.next = newNext;
this.listLen -= 1;
};
var reverseList = function(head) {
let p0 = head, p1 = head?.next;
if (p1) p0.next = null;
while(p1) {
const newNext = p1.next;
p1.next = p0;
p0 = p1;
p1 = newNext;
}
return p0;
};