原创

[百战LeetCode][15.判断一个链表是否为回文结构]


==========================努力奋斗财源广进==========================

一、算法题目

给定一个链表,请判断该链表是否为回文结构。回文是指该字符串正序逆序完全一致。

二、题解

1、我的题解

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        //比较简单
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = head;
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }
        while(!stack.isEmpty()){
            if(stack.pop().val != head.val){
                return false;
            }
            head = head.next;
        }
        return true;
    }
}

2、优秀题解

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public ListNode reverse(ListNode head){
        ListNode newHead = null;
        ListNode cur = head;
        while(cur != null){
            ListNode tem = cur.next;
            cur.next = newHead;
            newHead = cur;
            cur = tem;
        }
        return newHead;
    }
    
    public boolean isPail (ListNode head) {
        // write code here
        if(head == null) return false;
        if(head.next == null) return true;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = head.next;
        ListNode slow = head;
        ListNode pre = dummy;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            pre = pre.next;
        }
        ListNode list2;
        if(fast == null){
            list2 = slow.next;
            pre.next = null;
        } else{
            list2 = slow.next;
            slow.next = null;
        }
        ListNode list1 = reverse(head);
        
        while(list1 != null){
            if(list1.val != list2.val){
                return false;
            }
            list1 = list1.next;
            list2 = list2.next;
        }
        return true;
    }
}

三、解法心得

此题解法比较简单,主要利用回文的特点。 优秀题解,使用双指针。

四、自我监督

评论区记录复习记录

算法刷题
  • 作者:北斗七点半联系作者
  • 发表时间:2022-07-17 23:22
  • 版权声明:禁止转载
  • 非公众号转发
  • 评论