Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

234. Palindrome Linked List

Posted on 2020-09-09 | Edited on 2021-01-22

LeetCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
private ListNode endOfFirstHalf(ListNode head){
ListNode fast=head,slow=fast;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
private ListNode reverseList(ListNode head){
ListNode prev=null,curr=head;
while(curr!=null){
ListNode nextNode=curr.next;
curr.next=prev;
prev=curr;
curr=nextNode;
}
return prev;
}
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;

ListNode endOfFirstHalfNode=endOfFirstHalf(head);
ListNode reversedSecondHalf=reverseList(endOfFirstHalfNode.next);

ListNode p1=head,p2=reversedSecondHalf;
while(p2!=null&&p1.val==p2.val){
p1=p1.next;
p2=p2.next;
}
return p2==null;
}
}

<1…192021…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%