2019-03-22-算法-进化(回文链表)

题目描述

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解题

思路1:直接利用List的顺序存储性,解题

/**
	 * 思路1:数组存储法
	 * 时间复杂度O(n),空间复杂度O(n)
	 * @param head
	 * @return
	 */
	public boolean isPalindrome1(ListNode head) {
		List<Integer> list = new ArrayList<Integer>();
        while(head!=null) {
        	list.add(head.val);
        	head=head.next;
        }
        int size = list.size();
        for(int i=0;i<size/2;i++) {
        	if(list.get(i).intValue() != list.get(size-1-i).intValue() ) {
        		return false;
        	}
        }
		return true;
    }

**思路2:**利用栈的入栈、出栈,改变集合顺序原理

public boolean isPalindrome(ListNode head) {
        Stack<Integer> s = new Stack<>();
        ListNode cur = head;
        //将整个链表入栈,之后出栈的顺序其实就是链表的逆序
        while(cur != null){
            s.push(cur.val);
            cur = cur.next;
        }
        cur = head;
        while(!s.isEmpty()){
            if(s.pop() != cur.val){
                return false;
            }
            cur = cur.next;
        }
        return true;
    }

思路3

/**
	 * 思路3:
	 * 1.快慢指针找到中间节点
	 * 2.反转后半段链表
	 * 3.顺序比较链表前后半段,都相等则为回文
	 * 时间复杂度O(n),空间复杂度O(1)
	 * @param head
	 * @return
	 */
	public boolean isPalindrome(ListNode head) {
		if(head == null) {
			return true;
		}
        ListNode slow = head, fast=head, mid=null;
        while(fast!=null && fast.next!=null) {
        	slow = slow.next;
        	fast = fast.next.next;
        }
        mid = slow;
        ListNode cur = mid, next = mid.next, nNext=null;
        //链表从中间截断
        cur.next = null;
        while (next != null) {
			nNext = next.next;
			next.next = cur;
			cur = next;
			next = nNext;
		}
        while(cur != null) {
        	if(head.val != cur.val) {
        		return false;
        	}
        	head = head.next;
        	cur = cur.next;
        }
        
		return true;
    }

猜你喜欢

转载自blog.csdn.net/zhaohong_bo/article/details/88732092