【LeetCode】第16天 - 234. 回文链表

简介: 【LeetCode】第16天 - 234. 回文链表

@[TOC]

题目描述

在这里插入图片描述

解题思路

  • 遍历链表,将每个节点值依次入栈;
  • 再次遍历链表,每访问一个节点就出栈一个元素,比较该节点值与出栈元素是否相等,不等返回false;
  • 成功遍历,返回true。

    代码实现

    /**
    * Definition for singly-linked list.
    * public class ListNode {
    *     int val;
    *     ListNode next;
    *     ListNode() {}
    *     ListNode(int val) { this.val = val; }
    *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    * }
    */
    class Solution {
         
      public boolean isPalindrome(ListNode head) {
         
          Stack<Integer> stack = new Stack<Integer>();
          ListNode temp = head;
          while(temp != null){
                 //遍历链表,入栈节点值
              stack.push(temp.val);
              temp = temp.next;
          }
          while(head != null){
         
              if(head.val != stack.pop()){
                 //依次比较节点值与出栈元素是否相等
                  return false;
              }
              head = head.next;
          }
          return true;
      }
    }
    
目录
相关文章
LeetCode | 234. 回文链表
LeetCode | 234. 回文链表
|
9月前
|
算法
算法题解-回文链表
算法题解-回文链表
|
9月前
每日一题——回文链表
每日一题——回文链表
|
9月前
|
机器学习/深度学习
leetcode-234:回文链表
leetcode-234:回文链表
42 0
|
9月前
面试题 02.06:回文链表
面试题 02.06:回文链表
35 0
|
计算机视觉
234.回文链表(LeetCode)
234.回文链表(LeetCode)
234.回文链表(LeetCode)
【Leetcode -234.回文链表 -160.相交链表】
【Leetcode -234.回文链表 -160.相交链表】
29 0
|
算法 C语言 C++
单链表OJ题:LeetCode--234.回文链表
LeetCode--234.链表的回文与牛客网--OR36.链表的回文结构联合解题过程,附带完整代码与图解。
11728 2
|
存储
图解LeetCode——234. 回文链表
图解LeetCode——234. 回文链表
134 1
|
存储
力扣 - 234、回文链表
力扣 - 234、回文链表
74 0