LeetCode 203
视频讲解链接: 手把手带你学会操作链表 | LeetCode:203.移除链表元素
思路:
- 移除链表元素不是真正的删除元素, 而是让前一个指针的 next 指向下下一个节点
- 可以设置一个虚拟头结点,原链表的所有节点可以按照统一的方式进行移除
代码举例:
var removeElements = function(head, val) {
let res = new ListNode(0, head)
let cur = res
while(cur.next){
if(cur.next.val === val){
cur.next = cur.next.next
continue
}
cur = cur.next
}
return res.next
};
LeetCode 707
视频讲解链接: 帮你把链表操作学个通透!LeetCode:707.设计链表
思路:
- get: 创建虚拟节点, 通过 while loop 找到 index 节点并返回
- addAtHead: 创建一个新节点 next 指向 head, 然后从新让 head 指向新节点 | 如果没有尾结点,也指向新节点
- addAtTail: 创建一个新节点, 让 tail 节点的 next 指向新节点, 然后从新让 tail 指向新节点 | 如果没有 tail 节点, head也指向新节点
- addAtIndex
- index为0则调用addAtHead, 为length则调用addAtTail
- 创建一个新节点, 找到 index 前一个节点, 并指向新节点 - 新节点的next 等于前一个节点的next
- deleteAtIndex
- index为0则head向后移动一位, 如果删除的这个节点同时是尾节点, tail = head
- 找到 index 前一个节点, 如果 index 等于 length, 那么更新 tail 为前一个节点
- index 前一个节点的 next = next.next
代码举例:
class ListNode{
constructor(val, next){
this.val = val
this.next = next
}
}
var MyLinkedList = function() {
this.length = 0
this.head = null
this.tail = null
};
MyLinkedList.prototype.getNode = function(index){
if(index < 0 || index >= this.length) return null
// 创建虚拟节点
let cur = new ListNode(0, this.head)
while(index-- >= 0){
cur = cur.next
}
return cur
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
if(index < 0 || index >= this.length) return -1
return this.getNode(index).val
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
let newHead = new ListNode(val, this.head)
this.head = newHead
if(!this.tail){
this.tail = newHead
}
this.length++
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
let newTail = new ListNode(val, null);
if (!this.tail) {
this.head = newTail;
} else {
this.tail.next = newTail;
}
this.tail = newTail;
this.length++;
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
if (index < 0 || index > this.length) return;
if(index === 0){
this.addAtHead(val)
return
}
if(index === this.length){
this.addAtTail(val)
return
}
let lastNode = this.getNode(index - 1)
lastNode.next = new ListNode(val, lastNode.next)
this.length++
};
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if (index < 0 || index >= this.length) return;
if (index === 0) {
this.head = this.head.next;
if (index === this.length - 1) {
this.tail = this.head;
}
this.length--;
return;
}
let preNode = this.getNode(index - 1);
if (index === this.length - 1) {
this.tail = preNode;
}
preNode.next = preNode.next.next;
this.length--;
};
LeetCode 206 反转链表
思路
- 使用双指针, 创建一个 prev = null, cur = head
- 让 cur.next = prev 然后 prev, cur 向后移动各一位
代码举例:
var reverseList = function(head) {
let prev = null
let cur = head
while(cur){
let temp = cur.next
cur.next = prev
prev = cur
cur = temp
}
return prev
};