回文链表

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

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

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


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsPalindrome(ListNode head) {
        //反转前端链表
        int num = 0;
        ListNode temp = head;
        while(temp != null)
        {
            num++;
            temp = temp.next;
        }
        
        int medioNum = num / 2;
        ListNode preNode = null;
        ListNode curNode = head;
        ListNode startNode = null;
        while(medioNum != 0)//反转前半段链表
        {
            temp = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = temp;
            medioNum--;
        }
        //此时,preNode为前半段的头结点,curNode为后半段的头结点
        if(num % 2 == 1)
        {
            //链表为奇数的情况下,中间的结点为公有结点不用检查
            curNode = curNode.next;
        }
        
        while(curNode != null)
        {
            if(curNode.val != preNode.val)
                return false;
            
            curNode = curNode.next;
            preNode = preNode.next;
        }
        
        return true;
        
    }
}


一次过,我都惊呆了,虽然不难。先遍历链表计算链表的长度,反转前半段的链表,然后逐个对比就可以了。


首页 我的博客
粤ICP备17103704号