2.判断链表是否为回文序列

示例1:

输入: 1->2->2->1

输出: true

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

Java

解题思路1:栈。将链表全部入栈,然后一边出栈,一边重新遍历链表,比较两者元素,只要有一个不同则不是回文序列

public static boolean isPalindromeByAllStack(ListNode head) {
    ListNode temp = head;
    Stack<ListNode> stack = new Stack();
    //先入栈
    while(temp != null){
        stack.push(temp);
        temp = temp.next;
    }
    //再出栈遍历
    while(head != null){
        if(head != stack.pop()){
            return false;
        }
    }
    return true;
}

解题思路2:通过双指针法来判断。通过找到链表的中间节点然后把链表后半部分反转,再用后半部分反转的链表和前半部分一个个比较即可

 public boolean isPalindrome(ListNode head) {
        ListNode fast = head, slow = head;
        //通过快慢指针找到中点
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //如果fast不为空,说明链表的长度是奇数个
        if (fast != null) {
            slow = slow.next;
        }
        //反转后半部分链表
        slow = reverse(slow);

        fast = head;
        while (slow != null) {
            //然后比较,判断节点值是否相等
            if (fast.val != slow.val)
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    //反转链表
    public ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

python

遍历链表,把所有节点上的元素都存储到列表中,然后用双指针解决

    def isPalindrome(self, head):
        cur, length = head, 0
        result = []
        # 遍历链表,把所有节点上的元素都存储到列表 result 中
        while cur is not None:
            length += 1
            result.append(cur.val)
            cur = cur.next
            # 定义2个指针,一个从头开始往后,另一个从最后开始往前
        left, right = 0, length - 1
        while left < right:
            if result[left] != result[right]:
                return False
            left += 1
            right -= 1
        return True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值