203. 移除链表元素:给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
直接遍历所有节点,如果节点值等于val就用node.next = node.next.next(相当于删除节点);问题是如果头节点就相等,此时想用node.next就麻烦了,因为没有node.next(prev)指向头节点的节点;既然头节点没有前置节点,那就构造一个前置节点返回的时候不返回这个构造节点就好了;具体代码实现如下:
var removeElements = function(head, val) {
const prev = new ListNode(0,head);
let cur = prev;
while(cur.next !== null){
if(cur.next.val ===val){
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return prev.next;
};
206. 反转链表,给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
链表反转主要是想清楚,怎么从原节点拿到当前节点cur,当前节点要拼接到结果节点的前面即cur.next = res;
var reverseList = function(head) {
let cur = head;
let res = null
while(cur){
const temp = cur.next;
cur.next = null;
if(res){
cur.next = res
}
res = cur;
cur = temp;
}
return res;
};
山重水复疑无路,柳暗花明又一村;