TreeviewCopyright © aleen42 all right reserved, powered by aleen42

06. 回文链表

https://leetcode-cn.com/problems/palindrome-linked-list-lcci/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-31 15:10:42
 * @LastEditTime: 2020-08-31 15:10:55
 * @Description: https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
 * @FilePath: \leetcode-googtech\面试题02\#06. 回文链表\Solution.java
 * @WebSite: https://algorithm.show/
 */

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {

    // 双指针法
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        // 遍历链表元素并将其存储到数组列表中
        ListNode currentNode = head;
        while(currentNode != null) {
            list.add(currentNode.val);
            currentNode = currentNode.next;
        }
        // 同时移动头指针和尾指针,并判断所指元素是否相同
        int front = 0, rear = list.size() - 1;
        while(rear > front) {
            if(!list.get(front).equals(list.get(rear))) {
                return false;
            }
            front++;
            rear--;
        }
        return true;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-31 15:10:47
LastEditTime: 2020-08-31 15:12:02
Description: https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
FilePath: \leetcode-googtech\面试题02\#06. 回文链表\Solution.py
WebSite: https://algorithm.show/
'''

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        values = []
        currentNode = head
        while currentNode is not None:
            values.append(currentNode.val)
            currentNode = currentNode.next
        return values == values[::-1] # values[::-1] : 将 values 数组中的元素顺序取反
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""