From 34f28a02392276dcffd8ca6ee5b0258d725496d7 Mon Sep 17 00:00:00 2001 From: Abhishek Chaudhary Date: Mon, 14 Oct 2019 23:09:40 +0530 Subject: [PATCH] Completed Palindrome in Java --- .../6. Palindrome/Palindrome.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Chapter - 2 - Linked List/6. Palindrome/Palindrome.java diff --git a/Chapter - 2 - Linked List/6. Palindrome/Palindrome.java b/Chapter - 2 - Linked List/6. Palindrome/Palindrome.java new file mode 100644 index 0000000..6aac0af --- /dev/null +++ b/Chapter - 2 - Linked List/6. Palindrome/Palindrome.java @@ -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; + } + } +} \ No newline at end of file