单向链表对称性判断

// 将一个数组转为链表[1,2] => {value:1,next:next}{value:2,next:null}
function init(arr) {
    if (arr.length == 0) {
        return null;
    }
    let head = {
        value: arr[0],
        next: null
    };
    let tail = head;
    for(let i = 1; i < arr.length; i++) {
        let current = {
            value: arr[i],
            next: null
        };
        tail.next = current
        tail = current;
    }
    return head;
}
// 打印链表内容
function print(pHead) {
    let h = pHead;
    let str = ''
    while(h != null) {
        str += h.value + ', ';
        h = h.next;
    }
    console.log(str);
}
// 单向链表反转123 => 321
function reverse(pHead) {
    if(!pHead) return pHead;

    let next = pHead.next
    let newHead = pHead;
    newHead.next = null;
    while(next) {
        let current = next;    
        next = next.next;
        current.next = newHead;
        newHead = current;
    }
    
    return newHead;
}

// check 单向链表是否对称12321
function check(pHead) {
    // console.log('----------------begin')
    if(!pHead || pHead.length == 0) {
        // console.log('[] is null')
        return true
    }
    // print(pHead);
    // print(reverse(pHead));

    let mid = pHead
    let tail = pHead.next
    while(tail){
        mid = mid.next
        tail = tail.next
        if(tail) {
            tail = tail.next
        }
    } 
    mid = reverse(mid)
    // print(mid)

    while(pHead && mid){
    
        if(pHead.value != mid.value) {
            return false;
        }
        pHead = pHead.next
        mid = mid.next
    }

    return true;
}
// 测试用例
console.log(check(init([])) == true);
console.log(check(init([1])) == true);
console.log(check(init([1,1])) == true);
console.log(check(init([1,4,1])) == true);
console.log(check(init([1,4,5,4,1])) == true);
console.log(check(init([1,4])) == false);
console.log(check(init([1,4,5])) == false);

你可能感兴趣的:(单向链表对称性判断)