Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed Palindrome in Java #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Chapter - 2 - Linked List/6. Palindrome/Palindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
class Palindrome {
static ListNode head = null;

public static ListNode reverse(ListNode head) {
if (head == null)
return head;

ListNode current = head;
ListNode temp;
while (current.next != null) {
temp = current.next.next;
current.next.next = head;
head = current.next;
current.next = temp;
}
return head;
}

public static void print(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}

public static void add(int data) {
if (head == null) {
head = new ListNode(data);
return;
}
ListNode curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = new ListNode(data);
}

public static void main(String[] args) {
add(3);
add(5);
add(31);
add(90);
add(43);

print(head);
head = reverse(head);
print(head);
}

static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}
}