-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_04.java
More file actions
111 lines (89 loc) · 2.28 KB
/
Copy pathLinked_List_04.java
File metadata and controls
111 lines (89 loc) · 2.28 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Check if a Linked List is a palindrome
class Linked_List {
Node head;
int size;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public void Add_Last(int data) {
size++;
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newNode;
}
public void Print_Linked_List() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " -> ");
curr = curr.next;
}
System.out.println("NULL");
}
public Node Reverse(Node head){
Node prev=head;
Node curr=prev.next;
while (curr!=null) {
Node next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
head.next=null;
return prev;
}
public Node getMiddleNode(Node head){
Node slow = head;
Node fast = head;
while(fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
public boolean check_Palindrome(Node head){
if(head==null || head.next==null){
return true;
}
Node middle=getMiddleNode(head);
Node new_head=Reverse(middle.next);
while(new_head!=null){
if(head.data!=new_head.data){
return false;
}
new_head=new_head.next;
head=head.next;
}
return true;
}
}
public class Linked_List_04 {
public static void main(String[] args){
Linked_List list=new Linked_List();
list.Add_Last(0);
list.Add_Last(1);
list.Add_Last(2);
list.Add_Last(3);
list.Add_Last(3);
list.Add_Last(2);
list.Add_Last(1);
list.Add_Last(0);
list.Print_Linked_List();
System.out.println(list.check_Palindrome(list.head));
}
}