【算法练习】链表

随机读取,数组完美,链表不行;
插入或删除,链表很在行,数组很笨。

奇偶链表

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

示例 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);

在这里插入图片描述
注意:不论headcurrentcurrent.nexttail,它们也是一个链表,而不是某个链表节点。

环路检测

给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值