# 链表的合并
真题描述:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有结点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
处理链表的本质,是处理链表结点之间的指针关系。
function ListNode(val) {
this.val = val
this.next = null
}
function mergeTowLists(l1, l2) {
// 定义头节点,确保链表可以访问到
const head = new ListNode()
let cur = head
while (l1 && l2) {
if (l1.val <= l2.val) {
cur.next = l1
l1 = l1.next
}else {
cur.next = l2
l2 = l2.next
}
cur = cur.next
}
// 处理链表不等长的情况
cur.next = l1 !== null ? l1 : l2
return head.next
}
# 链表结点的删除
真题描述:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
判断两个元素是否重复,由于此处是已排序的链表,我们直接判断前后两个元素值是否相等即可。
function deleteDuplicates(head) {
let cur = head
while (cur !== null && cur.next !== null) {
if (cur.val === cur.next.val) {
// 删除操作
cur.next = cur.next.next
}else {
cur = cur.next
}
}
return head
}
# 删除问题的延伸——dummy 结点登场
真题描述:给定一个排序链表,删除所有含有重复数字的结点,只保留原始链表中没有重复出现的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
const list = {
val: 1,
next: {
val: 1,
next: {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: null
}
}
}
}
}
function ListNode(val) {
this.val = val
this.next = null
}
function deleteDuplicates(head) {
if (!head || !head.next) return head
let dummy = new ListNode()
dummy.next = head
let cur = dummy
while(cur.next && cur.next.next) {
if (cur.next.val === cur.next.next.val) {
let val = cur.next.val
while(cur.next && cur.next.val === val) {
cur.next = cur.next.next
}
}else {
cur = cur.next
}
}
return dummy.next
}
console.log(deleteDuplicates(list))