给定一个链表,请判断该链表是否为回文结构。
遍历(将链表分成两部分进行比较)
创建两个与原链表相同的链表,first和slow,first指针每次移动两次,slow指针每次移动一次,当first移动至null时,该链表为偶数个,如果不为null,则是奇数个,可以自己画图验证,当奇数个时 ,应该执行slow=slow.next移动至下一位,此时才是后半部分的链表,反转后进行比较值是否相等
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) { ListNode fast = head, slow = head; //通过快慢指针找到中点 while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } //如果fast不为空,说明链表的长度是奇数个 if (fast != null) { slow = slow.next; } //反转后半部分链表 slow = reverse(slow); fast = head; while (slow != null) { //然后比较,判断节点值是否相等 if (fast.val != slow.val) return false; fast = fast.next; slow = slow.next; } return true; } //反转链表 public ListNode reverse(ListNode head) { ListNode prev = null; while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; } return prev; } }
使用栈先进后出的特点,比较值是否相等,判断是否为回文串
public boolean isPail(ListNode head) { if (head == null) return true; ListNode temp = head; Stack<Integer> stack = new Stack(); //链表的长度 int len = 0; //把链表节点的值存放到栈中 while (temp != null) { stack.push(temp.val); temp = temp.next; len++; } //len长度除以2 len =len/2; //然后再出栈 while (len-- >= 0) { if (head.val != stack.pop()) return false; head = head.next; } return true; }
来源:剑指offer
链接:https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f?tpId=117&&tqId=37813