题目:
题目链接:两两交换链表中的节点
题解:
迭代
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
let swapPairs = function(head) {
let newNode = new ListNode(0,head)
let cur = head
let pre = newNode
while(cur && cur.next){
let next = cur.next
cur.next = next.next
next.next = cur
pre.next = next
pre = cur
cur = cur.next
}
return newNode.next
};
递归
如果链表中至少有两个节点,则在两两交换链表中的节点之后,原始链表的头节点变成新的链表的第二个节点,原始链表的第二个节点变成新的链表的头节点。链表中的其余节点的两两交换可以递归地实现。在对链表中的其余节点递归地两两交换之后,更新节点之间的指针关系,即可完成整个链表的两两交换。
let swapPairs = function(head) {
if (head === null|| head.next === null) {
return head;
}
const newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
};
删除链表的倒数第N个结点
题目:
题目链接:删除链表的倒数第N个结点
题解:
使用双指针,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了
几个关键点:
-
使用虚拟头结点,这样方便处理删除实际头结点的逻辑
-
fast首先走n + 1步,只有这样同时移动的时候slow才能指向删除节点的上一个节点(方便做删除操作)
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
var removeNthFromEnd = function(head, n) {
let newNode = new ListNode(1,head)
let fast = newNode
let slow = newNode
for(let i=0;i<=n;i++){
slow = slow.next
}
while(tail !=null){
fast = fast.next
slow = slow.next
}
fast.next = fast.next.next
return newNode.next
};