回文链表
2016-07-12 21:14
197 查看
题目
设计一种方式检查一个链表是否为回文链表。解题
回文串的特征就是正反看结果都一样如:aba、abcsdffdscba
所有翻转链表后比较
但是翻转链表改变了原始链表之间的指针
需要先复制原始链表
复制链表和选择链表进行比较
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @return a boolean */ public boolean isPalindrome(ListNode head) { // Write your code here if(head == null || head.next == null) return true; ListNode p = head; ListNode curHead = copy(head); ListNode revHead = reverse(p); boolean flag= compare(curHead,revHead); return flag; } public boolean compare(ListNode l1,ListNode l2){ while(l1!=null && l2!=null){ if(l1.val!=l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } public ListNode copy(ListNode head){ ListNode curHead = new ListNode(-1); ListNode cur = curHead; ListNode p = head; while(p!=null){ cur.next = new ListNode(p.val); p = p.next; cur = cur.next; } return curHead.next; } public ListNode reverse(ListNode head){ ListNode revHead = null; ListNode cur = null; ListNode p = head; while(p!=null){ ListNode pNext = p.next; if(pNext==null){ revHead = p; } p.next = cur; cur = p; p = pNext; } return revHead; } }
相关文章推荐
- java基础知识篇2
- 等号赋值与memcpy的效率问题
- 使用Clean() 去掉由函数自动生成的字符串中的双引号
- npm 私服(上)
- 写了一个合并的,大家可以参考下
- Codeforces Round #361 (Div. 2) C. Mike and Chocolate Thieves 二分
- python编写IP地址与十进制IP转换脚本
- 【Leetcode】371. Sum of Two Integers
- Android简易实战教程--第七话《在内存中存储用户名和密码》
- Android简易实战教程--第七话《在内存中存储用户名和密码》
- 如何通过linux ssh远程linux不用输入密码登入
- java动态代理框架
- 使用System.Drawing.Imaging.dll进行图片的合并
- <Spark>制作Spark-On-Yarn镜像
- HTTP的会话有四个过程,请选出不是的一个()----百度2016研发工程师笔试题(六)
- 台湾清华大学彭明辉教授的研究生手册(如何阅读论文)
- (Eclipse) 安装Subversion1.82(SVN)插件
- windows的DOS窗口如何修改大小
- 创建一个会滚动的textView
- 【Frame Animation 逐帧动画】