【Java】编写函数,检查链表是否为回文

来源:互联网 发布:苏州嘉图软件 编辑:程序博客网 时间:2024/05/16 16:19

快行指针找到链表中间结点

1. 反转前半部分看是否和后半部分一样

2. 将前半部分入栈,迭代访问剩下的一半结点,每次的栈顶元素一样则是回文链表


import java.util.Stack;public class isHuiWen {public boolean isPalinddrome(LinkedListNode head) {LinkedListNode fast = head;LinkedListNode slow = head;Stack<Integer> stack = new Stack<Integer>();while( fast != null && fast.next != null ) {stack.push(slow.data);slow = slow.next;fast = fast.next.next;}//如果链表有奇数个元素,那么fast这时不为空,则比较后半段时跳过中间元素if ( fast != null ) {slow = slow.next;}while (slow != null) {int top = stack.pop().intValue();//如果不相同,则不是回文if (top != slow.data) {return false;}slow= slow.next;}return true;}}


递归的解法:

class Result{public LinkedListNode node;public boolean result;}Result isPalindromeRecurse(LinkedListNode head, int length) {if (head == null || length == 0) {return new Result(null, true);}else if(length == 1) {return new Result(head.next,true);}else if(length == 2) {return new Result(head.next.next, head.data == head.next.data);}Result res = isPalindromeRecurse(head.next, length -2);if(!res.result || res.node == null){return res;}else{res.result = head.data == res.node.data;res.node = res.node.next;return res;}}boolean isPalinddrome(LinkedListNode head) {Result p = isPalindromeRecurse(head, listSize(head));return p.result;}



0 0
原创粉丝点击