Reprint please indicate the source http://www.cnblogs.com/haozhengfei/p/abb04e825ba4b847dcb704605ea1cd36.html
the palindrome structure of the linked list
Chain list palindrome structure exercisesThe 9th section List of palindrome structure exercises
Please write a function to check if the list is a palindrome.
Given a list of listnode* Phead, return a bool that indicates whether the linked list is a palindrome.
Test examples:
{1,2,3,2,1}
Return: True
{1,2,3,2,3}
Return: False
Java (javac 1.7)Code Auto-Complete1
Import Java. util. *;
2
3
/*
4
public class ListNode {
5
int Val;
6
ListNode next = null;
7
8
ListNode (int val) {
9
This.val = val;
10
}
11
}*/
12
Public class palindrome {
13
Public Boolean Ispalindrome (listnodephead{
14
if (phead= =null| | Phead. Next == null)
15
return false;
16
17
ListNode Slow = Phead;
18
ListNode Quick = Phead;
19
Stack < Integer > Stack = New Stack <> ();
20
while (quick!=null&&quick.) Next != null) {
21st
Stack. Push (slow. Val);
22
Slow = Slow. next;
23
Quick = Quick. next. next;
24
}
25
/**
26
* 5 7 3 2 3 7 5
27
* 4 3 2 1 1 2 3 4
28
*/
29
if (quick!=null&&quick.) Next == null) {
30
Slow = Slow. next;
31
Stack.pop ();
32
}
33
while (! Stack. IsEmpty && Slow != null) {
34
int Val = Stack. Pop ();
35
System.out.print (val + "");
36
if (val!=slow. Val)
37
return false;
38
Slow = Slow. next;
39
}
40
return true;
41
}
42
}
Your code is saved
The answer is right: Congratulations! The program you submitted passed all of the test casesRun
Algorithm--palindrome structure of linked list