TreeviewCopyright © aleen42 all right reserved, powered by aleen42

234. 回文链表

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

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-22 17:45:44
 * @Description: https://leetcode-cn.com/problems/palindrome-linked-list/
 * @FilePath: \leetcode-googtech\#234. Palindrome Linked List\Solution.java
 */ 

/**
 * 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-07-22 17:45:49
@Description: https://leetcode-cn.com/problems/palindrome-linked-list/
@FilePath: \leetcode-googtech\#234. Palindrome Linked List\Solution.py
'''
# 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 ""