LeetCode_234.回文链表

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

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

C#代码

/**
 * 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) 
    {
        if(head==null){
            return true;
        }

        List<int> list = new List<int>();
        while(head!=null)
        {
            list.Add( head.val);
            head = head.next;
        }

        int count = list.Count;
        int mid = count / 2;
        for(int i = 0; i < mid ; i++)
        {
            if(list[i]!=list[count-i-1])
            {
                return false;
            }
        }
        return true;
    }
}
posted @ 2021-01-07 09:00  付旭洋  阅读(42)  评论(0编辑  收藏  举报