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

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

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

import java.util.*;

class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public ListNode() {
    }



}

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail(ListNode head) {
        // write code here
        if (head == null) {
            return true;
        }
//      构建一个新的链表,然后把原来的链表复制到新的链表中.
        ListNode ListNode = DeepCopyListNode(head);
//      反转链表
        ListNode revserListNode = reserverNode(ListNode);

        int i = ListNodeLenth(revserListNode);
//        中心点
        int middle = i / 2;
        int o = 0;

        ListNode ListNode_index = head;
        ListNode revserListNode_index = revserListNode;

        while (o < middle) {
            if (ListNode_index.val != revserListNode_index.val) {
                return false;
            }

            ListNode_index = ListNode_index.next;
            revserListNode_index = revserListNode_index.next;
            o++;
        }


        return true;

    }
    public ListNode DeepCopyListNode(ListNode next) {
        //   指向第一个首元节点.
        ListNode listNode = next;
//      指向第二个.

        ListNode two_head = new ListNode(0, null);
        ListNode two_temp = two_head;
        while (listNode != null) {
            ListNode listNode1 = new ListNode(listNode.val, null);
            two_head.next = listNode1;
            two_head = two_head.next;
            listNode = listNode.next;
        }

        return two_temp.next;
    }

    public ListNode reserverNode(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;


        while (cur != null) {
//            存入下一个节点
            next = cur.next;
//
            cur.next = pre;
            pre = cur;
            cur = next;
        }


        return pre;
    }
    public int ListNodeLenth(ListNode pHead) {
        if (pHead == null) {
            return 0;
        }
        ListNode temp = pHead;
        int len = 1;
        while (temp.next != null) {
            temp = temp.next;
            len++;
        }
        return len;
    }

}
  1. 两个链表一个不做处理,另一个做反转.
  2. 之后得出长度,之后处于2.例如10/2=5 需要进行5次更换. i=0/5;
  3. 可以对比出第一个和最后一个的数据,不断++;
全部评论

相关推荐

码农索隆:力扣的题目还挺贴近现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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