牛客刷题-面试笔刷TOP101-6 判断一个链表是否为回文结构

判断一个链表是否为回文结构

给定一个链表,请判断该链表是否为回文结构。

回文是指该字符串正序逆序完全一致。

数据范围: 链表节点数 0≤n≤105,链表中每个节点的值满足 ∣val∣≤107

示例1

输入:

{1}

返回值:

true

示例2

输入:

{2,1}

返回值:

false

说明:

2->1     

示例3

输入:

{1,2,2,1}

返回值:

true

说明:

1->2->2->1     

解法1:转换为数组

  • 首先初始化一个list列表;
  • 遍历链表,将链表中的值转移至list中;
  • 在list中通过比较头尾的值来判断链表是否为回文结构

请添加图片描述

    public bool isPail (ListNode head) {
        // write code here
        //只有一个结点一定是回文结构
        if(head.next == null) return true;
        List<int> list = new List<int>();
        while(head != null)
        {
            list.Add(head.val);
            head = head.next;
        }
        int left = 0,right = list.Count - 1;
        while(left < right)
        {
            if(list[left] != list[right]) return false;
            left++;
            right--;
        }
        return true;
    }

解法2:反转后半部分链表

    public bool isPail (ListNode head) {
        // write code here
        //只有一个结点一定是回文结构
        if(head.next == null) return true;
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null)
        {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 如果fast 为空,则链表长度为偶数个,否则链表长度为奇数个
        if(fast != null)
        {
            slow = slow.next;
        }
        //反转后半部分链表
        slow = ReversListNode(slow);
        fast = head;
        while(slow != null)
        {
            //开始比较
            if(slow.val != fast.val) return false;
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }

    public ListNode ReversListNode(ListNode node)
    {
        ListNode head = null;
        while(node != null)
        {
            ListNode temp = node.next;
            node.next = head;
            head = node;
            node = temp;
        }
        return head;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值