21.合并两个有序链表
链表结构
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
//递归
var mergeTwoLists = function (l1, l2) {
if(l1===null){
return l2
}
else if(l2===null){
return l1
}
else if(l1.val<l2.val){
l1.next=mergeTwoLists(l1.next,l2)
return l1
}else{
l2.next=mergeTwoLists(l1,l2.next)
return l2
}
};
//迭代
var mergeTwoLists = function (l1, l2) {
let res = new ListNode()
let l3=res
while (l1 && l2) {
if (l1.val < l2.val) {
l3.next=l1
l1 = l1.next
} else {
l3.next=l2
l2 = l2.next
}
l3=l3.next
}
l3.next=(l1?l1:l2);
return res.next
};
19.删除链表的倒数底n个节点
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
//双指针,快慢指针
var removeNthFromEnd = function (head, n) {
let fast=head,
sort=head
while(n-->0){
fast=fast.next
}
if(fast==null) return head.next
while(fast.next){
fast=fast.next
sort=sort.next
}
sort.next=sort.next.next
return head
};
//递归
let con = 0
var removeNthFromEnd = function (head, n) {
if (head == null) return null
head.next = removeNthFromEnd(head.next, n)
con++
if (n == con) return head.next;
return head;
};
24.交换链表的相邻节点
var swapPairs = function(head) {
let res= new ListNode()
res.next=head
let t=res
while(t.next&&t.next.next){
let l=t.next
r=t.next.next
t.next=r
l.next=r.next
r.next=l
t=l
}
return res.next
};