题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ // 回文结构分析 如果是 1 2 3 2 1 1 2 1 2 12345 public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head * @return bool布尔型 */ public void printList(ListNode head) { ListNode current = head; while (current != null) { System.out.print(current.val + " -> "); current = current.next; } } public boolean isPail (ListNode head) { Stack<ListNode>stack1 = new Stack<>(); ListNode p = head; while (p != null) { ListNode newNode = new ListNode(p.val); stack1.push(newNode); p = p.next; } ListNode dummy = new ListNode(0); ListNode q = dummy; while (!stack1.isEmpty()) { ListNode temp = stack1.pop(); q.next = temp; q = q.next; } q.next = null; // printList(dummy.next); ListNode first = head,second = dummy.next; printList(first); while (first.val == second.val) { first = first.next; second = second.next; if (first == null && second == null) { return true; } else if ((first == null && second != null) || (first != null && second == null) ) { return false; } } return false; } }
出现问题
1.出现了一个很智障的错误,我把链表入栈,就等于把原有的链表销毁了,然后我又将原有链表和新链表比较哈哈哈
2.出栈转为链表的时候记得设置最后一个节点的next指向空
回文用入栈出栈比较好做,刚开始想到的时快慢指针,,,后面想了很久,没思路,先记下。。。