234. Palindrome Linked List

LeetCode easy original: C# #array #csharp #easy #leetcode #linked-list #string
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.

Дан головной element односвязного списка. return true, если список является палиндромом, и false в противном случае.

Esempio

Input: head = [1,2,2,1]

Output: true

C# soluzione

abbinato/originale
public class Solution {
    public bool IsPalindrome(ListNode head) {
        List<int> vals = new List<int>();
        ListNode currentNode = head;
        while (currentNode != null) {
            vals.Add(currentNode.val);
            currentNode = currentNode.next;
        }
        int front = 0;
        int back = vals.Count - 1;
        while (front < back) {
            if (vals[front] != vals[back]) {
                return false;
            }
            front++;
            back--;
        }
        return true;
    }
}

C++ soluzione

bozza automatica, rivedere prima dell'invio
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public bool IsPalindrome(ListNode head) {
        List<int> vals = new List<int>();
        ListNode currentNode = head;
        while (currentNode != null) {
            vals.push_back(currentNode.val);
            currentNode = currentNode.next;
        }
        int front = 0;
        int back = vals.size() - 1;
        while (front < back) {
            if (vals[front] != vals[back]) {
                return false;
            }
            front++;
            back--;
        }
        return true;
    }
}

Java soluzione

abbinato/originale
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> vals = new ArrayList<>();

        ListNode currentNode = head;
        while (currentNode != null) {
            vals.add(currentNode.val);
            currentNode = currentNode.next;
        }

        int front = 0;
        int back = vals.size() - 1;
        while (front < back) {
            if (!vals.get(front).equals(vals.get(back))) {
                return false;
            }
            front++;
            back--;
        }
        return true;
    }
}

JavaScript soluzione

abbinato/originale
class Solution {
    isPalindrome(head) {
        let vals = []
        let currentNode = head

        while (currentNode !== null) {
            vals.push(currentNode.val)
            currentNode = currentNode.next
        }

        let front = 0
        let back = vals.length - 1
        while (front < back) {
            if (vals[front] !== vals[back]) {
                return false
            }
            front++
            back--
        }
        return true
    }
}

Python soluzione

abbinato/originale
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        vals = []
        currentNode = head

        while currentNode is not None:
            vals.append(currentNode.val)
            currentNode = currentNode.next

        front = 0
        back = len(vals) - 1
        while front < back:
            if vals[front] != vals[back]:
                return False
            front += 1
            back -= 1
        return True

Go soluzione

abbinato/originale
func isPalindrome(head *ListNode) bool {
    vals := []int{}
    currentNode := head

    for currentNode != nil {
        vals = append(vals, currentNode.Val)
        currentNode = currentNode.Next
    }

    front := 0
    back := len(vals) - 1
    for front < back {
        if vals[front] != vals[back] {
            return false
        }
        front++
        back--
    }
    return true
}

Algorithm

Копирование односвязного списка в array: Итеративно пройдите по односвязному списку, добавляя каждое значение в array. Для этого используйте переменную currentNode, указывающую на текущий узел. На каждой итерации добавляйте currentNode.val в array и обновляйте currentNode, чтобы он указывал на

currentNode.next

. Остановите цикл, когда currentNode укажет на null.

Проверка arrayа на палиндром: Используйте метод с двумя указателями для проверки arrayа на палиндром. Разместите один указатель в начале arrayа, а другой в конце. На каждом шаге проверяйте, равны ли значения, на которые указывают указатели, и перемещайте указатели к центру, пока они не встретятся.

Сравнение значений: Помните, что необходимо сравнивать значения узлов, а не сами узлы. Используйте node_1.val == node_2.val для сравнения значений узлов. Сравнение узлов как объектов node_1 == node_2 не даст ожидаемого результата.

😎

Vacancies for this task

offerte attive with overlapping task tags are mostrati.

Tutte le offerte
Non ci sono ancora offerte attive.