链表---判断一个链表是否为回文链表

思路1:找到中间节点然后把后面的翻转,(需要断开链表)然后比较和头节点开始的前段,最后要是后半段的游标可以走到最后说明是回文否则不是

思路2:整体翻转比较

思路3:借助一个栈存放前半段的元素,然后和后半段的比较

public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null ) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode second = slow.next;
        slow.next = null;

        ListNode secondhead = null;
        ListNode p = second;
        while (p != null) {
            ListNode temp = p.next;
            p.next = secondhead;
            secondhead = p;
            p = temp;
        }

        ListNode p1 = head;
        ListNode p2 = secondhead;
        while (p2 != null && p2.val == p1.val) {
            p1 = p1.next;
            p2 = p2.next;
        }
        if (p2 == null) {
            return true;
        } else {
            return false;
        }
    }
递归实现
递归的终止条件:
当长度为0或者1的时候表明链表处于中间位置
class Result{
    public ListNode node;
    public boolean result;
    public Result(ListNode node,boolean res) {
        this.node = node;
        this.result=res;
    }
}

public Result ispalindromeResourse(ListNode head,int length) {
        if (head == null || length == 0) {
            return new Result(null,true);
        } else if (length == 1 ){
            return new Result(head.next,true);
        } else if (length == 2) {
            return new Result(head.next.next,head.val == head.next.val);
        }
        Result res = ispalindromeResourse(head.next,length-2);
        if (!res.result || res.node==null) {
            return res;
        } else {
            res.result = head.val == res.node.val;
            res.node = res.node.next;
            return res;
        }
    }
}
结果就是返回值的result

猜你喜欢

转载自blog.csdn.net/l1394049664/article/details/81350146