版权声明: https://blog.csdn.net/qq_38386316/article/details/83017044
题目描述
请判断一个链表是否为回文链表。
示例 1
- 输入:
- 输出:
示例 2
- 输入:
- 输出:
思路 * 1
使用数组存储所有结点的值,然后利用一个循环进行值的比较就可以了。
代码 * 1
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;
int[] a= new int[50000];
int i=0;
while(head!=null){
a[i++]=head.val;
head=head.next;
}
boolean flag=true;
for(int j=0;j<i/2;j++){
if(a[j]!=a[i-j-1]){
flag=false;
break;
}
}
return flag;
}
}
思路 * 2
使用快慢指针的思路首先求出中间结点 偶数个时,偏右的那个结点
,把从slow指针的结点开始的链表进行翻转.
然后让反转后的链表和原始链表的前半段进行值的比较,不同的话直接返回false,否则返回true。
代码 * 2
class Solution {
public boolean isPalindrome(ListNode head){
ListNode fast = head, slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
slow = reverse(slow);
fast = head;
while(slow != null) {
if(fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode prev = null;
while(head != null) {
ListNode nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
完整代码
package leetcode234;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by 张超帅 on 2018/10/11.
*/
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val;}
}
class Solution {
public boolean isPalindrome(ListNode head){
ListNode fast = head, slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
slow = reverse(slow);
fast = head;
while(slow != null) {
if(fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode prev = null;
while(head != null) {
ListNode nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
}
public class leetcode234 {
public static int[] stringToArrays(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if(input == null) {
return new int[0];
}
String[] parts = input.split(",");
int[] res = new int[parts.length];
for(int i = 0; i < parts.length; i ++) {
res[i] = Integer.parseInt(parts[i].trim());
}
return res;
}
public static ListNode stringToListNode(String input) {
int[] nodes = stringToArrays(input);
ListNode dummpy = new ListNode(-1);
ListNode cur = dummpy;
for(int node : nodes) {
cur.next = new ListNode(node);
cur = cur.next;
}
return dummpy.next;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = in.readLine()) != null) {
ListNode head = stringToListNode(line);
Boolean result = new Solution().isPalindrome(head);
System.out.println(result);
}
}
}