随机读取,数组完美,链表不行;
插入或删除,链表很在行,数组很笨。
奇偶链表
给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
示例 2:
输入: 2->1->3->5->6->4->7->NULL
输出: 2->3->6->7->1->5->4->NULL
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
var oddEvenList = function(head) {
if(!head) return head;
var list = head;
var current = tail = head.next;
while(current && current.next){
head.next = current.next;
current.next = current.next.next;
head.next.next = tail;
head = head.next;
current = current.next;
}
return list;
};
var list = new ListNode(
2,
new ListNode(1,
new ListNode(3,
new ListNode(5,
new ListNode(6,
new ListNode(4,
new ListNode(7,null)
)
)
)
)
)
)
var res = oddEvenList(list);
console.log(res);
注意:不论head
、current
、current.next
、tail
,它们也是一个链表,而不是某个链表节点。
环路检测
给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next
元素指向在它前面出现过的节点,则表明该链表存在环路。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
function ListNode(val) {
this.val = val;
this.next = null;
}
function detectCycle(head) {
let current = head;
const map = new Map();
let index = 0;
while(current && map.get(current)===undefined){
map.set(current,index++);
current = current.next;
}
return current;
};
const node0 = new ListNode(3);
const node1 = new ListNode(2);
const node2 = new ListNode(0);
const node3 = new ListNode(-4);
node0.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node1;
const res = detectCycle(node0);
console.log(res);