题解 | 判断一个链表是否为回文结构

判断一个链表是否为回文结构

https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {

    public ListNode copyList(ListNode head) {
        ListNode copy = new ListNode(-1);
        ListNode res = copy;
        while (head != null) {
            res.next = new ListNode(head.val);
            res = res.next;
            head = head.next;
        }
        return copy.next;
    }

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)return head;
        ListNode pre = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
       return pre;
    }

    public boolean isPail (ListNode head) {
        ListNode head_ = copyList(head);
        ListNode _head = reverseList(head);
        while (head_ != null) {
            if (head_.val != _head.val) {
                return false;
            }
            head_ = head_.next;
            _head = _head.next;
        }
        return true;
    }
}

全部评论

相关推荐

02-05 17:50
已编辑
武汉工程科技学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务