Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit87860db

Browse files
Create 234. Palindrome Linked List.java
1 parent5be3c73 commit87860db

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//reverse the later half
2+
//after reversing just start comparing if at any time the value doesn't match it's not a palindrome, i.e. return false, else it's a palindrome and return true.
3+
//It'll automatically take care of the edge cases of odd and even
4+
5+
classSolution {
6+
publicbooleanisPalindrome(ListNodehead) {
7+
ListNodefast =head;
8+
ListNodeslow =head;
9+
while (fast !=null &&fast.next !=null) {
10+
fast =fast.next.next;
11+
slow =slow.next;
12+
}
13+
ListNodetemp =reverse(slow);
14+
while (temp!=null &&head!=null) {
15+
if (temp.val !=head.val)
16+
returnfalse;
17+
temp =temp.next;
18+
head =head.next;
19+
}
20+
returntrue;
21+
}
22+
23+
publicListNodereverse(ListNodehead) {
24+
ListNodep =null;
25+
ListNodeq =null;
26+
ListNoder =head;
27+
while (r!=null) {
28+
p =q;
29+
q =r;
30+
r =r.next;
31+
q.next =p;
32+
}
33+
returnq;
34+
}
35+
36+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp