判断单链表回文
2016-05-22 18:12
274 查看
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null){ return true; } ListNode reverseHead = new ListNode(head.val); reverseHead.next = null; ListNode curr = head.next; ListNode nextNode; int count = 0; while (head != null){ count++; head = head.next; } int n = count/2; while (--n > 0){ nextNode = curr.next; curr.next = reverseHead; reverseHead = curr; curr = nextNode; } if(count%2 == 1){ curr = curr.next; } while (curr != null){ if(curr.val != reverseHead.val){ return false; } curr = curr.next; reverseHead = reverseHead.next; } return true; } public static void main(String[] args){ ListNode head = new ListNode(1); ListNode one = new ListNode(2); ListNode two = new ListNode(3); ListNode three = new ListNode(2); ListNode four = new ListNode(1); head.next = one; one.next = two; two.next = three; three.next = four; four.next = null; System.out.println(new Solution().isPalindrome(head)); } }
相关文章推荐
- C#定义并实现单链表实例解析
- C#数据结构之单链表(LinkList)实例详解
- C#实现回文检测的方法
- C语言实现单链表逆序与逆序输出实例
- C语言单链表常见操作汇总
- PHP输出两个数字中间有多少个回文数的方法
- C数据结构之单链表详细示例分析
- C++中单链表的建立与基本操作
- 深入单链表的快速排序详解
- C语言创建和操作单链表数据结构的实例教程
- C语言单链表的实现
- PHP判断一个字符串是否是回文字符串的方法
- java实现单链表中是否有环的方法详解
- java实现单链表、双向链表
- java判断回文数示例分享
- Python单链表的简单实现方法
- Python单链表简单实现代码
- Go语言单链表实现方法
- Python单链表简单实现代码
- 结构之美:在单链表指定位置插入数据