博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 234. Palindrome Linked List
阅读量:4321 次
发布时间:2019-06-06

本文共 2043 字,大约阅读时间需要 6 分钟。

原题链接在这里:

题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:

Could you do it in O(n) time and O(1) space?

题解:

原题要求time O(n), space O(1). 所以不能用额外空间。

先找到中点, reverse中点后面的list部分,再与head开始逐个比较val. 其中reverse部分可以参见.

Time Complexity: O(n). Space O(1).

AC Java:

1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { val = x; } 7  * } 8  */ 9 class Solution {10     public boolean isPalindrome(ListNode head) {11         if(head == null || head.next == null){12             return true;13         }14         15         ListNode mid = findMid(head);16         ListNode midNext = mid.next;17         mid.next = null;18         19         midNext = reverse(midNext);20         21         while(head != null && midNext != null){22             if(head.val != midNext.val){23                 return false;24             }25             26             head = head.next;27             midNext = midNext.next;28         }29         30         return true;31     }32     33     private ListNode findMid(ListNode head){34         if(head == null || head.next == null){35             return head;36         }37         38         ListNode runner = head;39         ListNode walker = head;40         while(runner.next != null && runner.next.next != null){41             walker = walker.next;42             runner = runner.next.next;43         }44         45         return walker;46     }47     48     private ListNode reverse(ListNode head){49         if(head == null || head.next == null){50             return head;51         }52         53         ListNode tail = head;54         ListNode cur = tail;55         ListNode pre;56         ListNode temp;57         while(tail.next != null){58             pre = cur;59             cur = tail.next;60             temp = cur.next;61             cur.next = pre;62             tail.next = temp;63         }64         65         return cur;66     }67 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825011.html

你可能感兴趣的文章
MySQL基于binlog主从复制
查看>>
HDU 1394(归并求逆序对)
查看>>
配置 Windows 下的 nodejs C++ 模块编译环境 安装 node-gyp
查看>>
我和Socket的第一次亲密接触
查看>>
2016/09/22
查看>>
2016/09/02
查看>>
项目中遇到的Redis缓存问题
查看>>
Effective Java 之-----静态工厂与构造器
查看>>
linux 命令(9) top
查看>>
Android消息处理(一)进程内通信
查看>>
利用office2010 word2010生成目录
查看>>
[ffmpeg 扩展第三方库编译系列] 关于libvpx mingw32编译问题
查看>>
虚拟现实技术对人类是福还是祸?
查看>>
P3106 GPS的决斗
查看>>
hdoj1164
查看>>
简单工厂模式
查看>>
Using关键字的用法
查看>>
标准C程序设计七---60
查看>>
[Silverlight入门系列]使用MVVM模式(4):Prism的NotificationObject自动实现INotifyPropertyChanged接口...
查看>>
工作用工具
查看>>