234. Palindrome Linked List
2016-06-25 10:36
330 查看
题目:https://leetcode.com/problems/palindrome-linked-list/
代码:
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { int length = getlength(head); int[] cur = new int[length]; int index = 0; while(head!=null) { cur[index++] = head.val; head = head.next; } int i=0,j=length-1; while(i<j) { if(cur[i]!=cur[j]) return false; i++;j--; } return true; } public int getlength(ListNode head) { int length=0; ListNode temp = head; while(temp!=null) { length++; temp = temp.next; } return length; } } 3ms ==============================用堆 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { int length = getlength(head); Stack<ListNode> temp = new Stack<>(); int flag = 0; while(flag!=length/2&&head!=null) { temp.push(head); head = head.next; flag++; } if(length%2!=0) head = head.next; while(head!=null) { ListNode cur = temp.pop(); if(head.val!=cur.val) return false; head = head.next; } return true; } public int getlength(ListNode head) { int length=0; ListNode temp = head; while(temp!=null) { length++; temp = temp.next; } return length; } } 4ms ====================dicuss里的一种解法: 翻转前半段 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { // traverse the list once to count the number of elements and determine the midpoint ListNode current = head; int nodeCount = 0; while (current != null) { nodeCount++; current = current.next; } int midCount = nodeCount/2; // reverse the first half of the list current = head; ListNode previous = null; ListNode temp = null; for (int ii = 0; ii < midCount; ii++) { temp = current.next; current.next = previous; previous = current; current = temp; } // if there are an odd number of elements, skip the middle element if (nodeCount % 2 == 1) { current = current.next; } // compare the second half of the list to the reversed first half // "previous" points to the head of the reversed first half for (int jj = 0; jj < midCount; jj++) { if (current.val != previous.val) { return false; } else { current = current.next; previous = previous.next; } } return true; } } 1ms
相关文章推荐
- xml解析器
- Python学习笔记
- 使用C语言打印不同星号图案(矩形 平行四边形 三角形)
- Java类属性的私有化
- 你看起来很厉害,所以一事无成
- DPDK内存管理 ----- (四) rte_mbuf
- SQL错误:将截断字符串或者二进制数据
- Linux修改密码
- 《七律·2016》
- 谈谈如何使用Netty开发实现高性能的RPC服务器
- 移动端表单验证
- 微信JSSDK上传多张图片
- Linux curl命令实例
- 公司mysql数据库设计与优化培训ppt
- 集成Activitie在线编辑器 Model
- 读薄《Linux 内核设计与实现》(3) - 系统调用
- Python--matplotlib绘图可视化知识点整理
- ASP.NET MVC+Bootstrap个人博客之praise.js点赞特效插件
- 初学CentOS——vi/vim编辑器
- 垃圾回收算法