算法day03

38 阅读1分钟

1.反转单链表

public LinkedList Reverse1(LinkedList head){
    if(head==null||head.next==null) return head;
    LinkedList rehead = Reverse1(head.getNext());
    head.getNext().setNext(head);
    head.setNext(null);
    return rehead;
}

public LinkedList Reverse2(LinkedList head){
    if(head==null||head.getNext()==null) return head;
    LinkedList pre = head;     //前一个
    LinkedList cur = head.next;     //当前节点
    LinkedList temp = cur.next;    //后一个
    pre.next = null;
    while(cur!=null){
        temp = cur.next;
        cur.setNext(pre);
        pre = cur;
        cur = temp;
        cur = cur.getNext();
    }
    return pre;
}

2.判断是否为回文链表

public boolean isPalindRome1(LinkedNode head) {
    if (head == null || head.next == null) return true;
    LinkedNode fast = head;
    LinkedNode slow = head;
    //找到链表中点位置
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    Stack<LinkedNode> stack = new Stack<>();
    while (slow.next != null) {
        slow = slow.next;
        stack.push(slow);
    }
    while (!stack.isEmpty()) {
        if (stack.pop().val != head.val) {
            return false;
        } else {
            head = head.next;
        }
    }
    return true;
}

public boolean isPalindRome2(LinkedNode head) {
    if (head == null || head.next == null) return true;
    LinkedNode fast = head;
    LinkedNode slow = head;
    boolean flag = true;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    fast = slow;
    slow = slow.next;
    fast.next = null;
    LinkedNode temp;
    while (slow != null) {
        temp = slow.next;
        slow.next = fast;
        fast = slow;
        slow = temp;
    }
    temp = fast;
    slow = head;
    while (fast != null && slow != null) {
        if (fast.val != slow.val) {
            flag = false;
            break;
        }
        fast = fast.next;
        slow = slow.next;
    }
    slow = temp.next;
    temp.next = null;
    while (slow != null) {
        fast = slow.next;
        slow.next = temp;
        temp = slow;
        slow = fast;
    }
    return flag;

}