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

it2026-02-18  5

例如 1 -> 3 -> 5 -> 3 ->  1 :为回文

public class Palindrome { public boolean isPalindrome(Node head){ if(head == null || head.next == null){ return true; } //获取链表的后半部分right Node right = head; Node cur = head; while(cur.next != null || cur.next.next != null){ right = right.next; cur = cur.next.next; } //将right压入栈中 Stack<Node> stack = new Stack<>(); while(right != null){ stack.push(right); right = right.next; } //链表左半部分值与栈中从上到下的值进行比较 while(!stack.isEmpty()){ if(head.value != stack.pop().value){ return false; } head = head.next; } return true; } public class Node{ int value; Node next; public Node(int date){ this.value = date; } } }

 

最新回复(0)