领扣——234.回文链表

领扣——234.回文链表

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

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
思路是翻转后一部分的链表,然后用双指针从每部分头开始比较,一样返回true,不一样返回false

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null)
            return true;
        int length=0;
        //初始化指向头结点
        ListNode tmp=head;
        while(tmp!=null){
            length++;
            tmp=tmp.next;
        }
        //算出链表中间的位置
        int halfLength=length/2;
        //把指针移到中间位置
        tmp=head;
        for(int i=0;i<halfLength;i++){
            tmp=tmp.next;
        }
        //开始反转后一部分的链表
        ListNode pre=tmp;
        ListNode pNode=tmp.next;
        ListNode next=null;
        while(pNode!=null){
            next=pNode.next;
            pNode.next=pre;
            pre=pNode;
            pNode=next;
        }
        //比较两部分链表的每个值是不是一样
        for(int i=0;i<halfLength;i++){
            if(head.val!=pre.val)
                return false;
            head=head.next;
            pre=pre.next;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/u010651249/article/details/83819712