Check if linked list is palindrome Python

Function to check if a singly linked list is palindrome

Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

METHOD 1 [Use a Stack]

  • A simple solution is to use a stack of list nodes. This mainly involves three steps.
  • Traverse the given list from head to tail and push every visited node to stack.
  • Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node.
  • If all nodes matched, then return true, else false.

Below image is a dry run of the above approach:



Below is the implementation of the above approach :

C++




#include

using namespace std;

class Node {

public:

int data;

Node[int d]{

data = d;

}

Node *ptr;

};

// Function to check if the linked list

// is palindrome or not

bool isPalin[Node* head]{

// Temp pointer

Node* slow= head;

// Declare a stack

stack s;

// Push all elements of the list

// to the stack

while[slow != NULL]{

s.push[slow->data];

// Move ahead

slow = slow->ptr;

}

// Iterate in the list again and

// check by popping from the stack

while[head != NULL ]{

// Get the top most element

int i=s.top[];

// Pop the element

s.pop[];

// Check if data is not

// same as popped element

if[head -> data != i]{

return false;

}

// Move ahead

head=head->ptr;

}

return true;

}

// Driver Code

int main[]{

// Addition of linked list

Node one = Node[1];

Node two = Node[2];

Node three = Node[3];

Node four = Node[2];

Node five = Node[1];

// Initialize the next pointer

// of every current pointer

five.ptr = NULL;

one.ptr = &two;

two.ptr = &three;

three.ptr = &four;

four.ptr = &five;

Node* temp = &one;

// Call function to check palindrome or not

int result = isPalin[&one];

if[result == 1]

coutnext;

// We need previous of the slow_ptr for

// linked lists with odd elements

prev_of_slow_ptr = slow_ptr;

slow_ptr = slow_ptr->next;

}

// fast_ptr would become NULL when there

// are even elements in list. And not NULL

// for odd elements. We need to skip the

// middle node for odd case and store it

// somewhere so that we can restore the

// original list

if [fast_ptr != NULL]

{

midnode = slow_ptr;

slow_ptr = slow_ptr->next;

}

// Now reverse the second half and

// compare it with first half

second_half = slow_ptr;

// NULL terminate first half

prev_of_slow_ptr->next = NULL;

// Reverse the second half

reverse[&second_half];

// compare

res = compareLists[head, second_half];

// Construct the original list back

reverse[&second_half]; // Reverse the second half again

// If there was a mid node [odd size case]

// which was not part of either first half

// or second half.

if [midnode != NULL]

{

prev_of_slow_ptr->next = midnode;

midnode->next = second_half;

}

else

prev_of_slow_ptr->next = second_half;

}

return res;

}

// Function to reverse the linked list

// Note that this function may change

// the head

void reverse[struct Node** head_ref]

{

struct Node* prev = NULL;

struct Node* current = *head_ref;

struct Node* next;

while [current != NULL]

{

next = current->next;

current->next = prev;

prev = current;

current = next;

}

*head_ref = prev;

}

// Function to check if two input

// lists have same data

bool compareLists[struct Node* head1,

struct Node* head2]

{

struct Node* temp1 = head1;

struct Node* temp2 = head2;

while [temp1 && temp2]

{

if [temp1->data == temp2->data]

{

temp1 = temp1->next;

temp2 = temp2->next;

}

else

return 0;

}

// Both are empty return 1

if [temp1 == NULL && temp2 == NULL]

return 1;

// Will reach here when one is NULL

// and other is not

return 0;

}

// Push a node to linked list. Note

// that this function changes the head

void push[struct Node** head_ref, char new_data]

{

// Allocate node

struct Node* new_node = [struct Node*]malloc[

sizeof[struct Node]];

// Put in the data

new_node->data = new_data;

// Link the old list off the new node

new_node->next = [*head_ref];

// Move the head to point to the new node

[*head_ref] = new_node;

}

// A utility function to print a given linked list

void printList[struct Node* ptr]

{

while [ptr != NULL]

{

cout data next;

}

cout next;

}

// Now reverse the second half and compare it with first half

second_half = slow_ptr;

prev_of_slow_ptr->next = NULL; // NULL terminate first half

reverse[&second_half]; // Reverse the second half

res = compareLists[head, second_half]; // compare

/* Construct the original list back */

reverse[&second_half]; // Reverse the second half again

// If there was a mid node [odd size case] which

// was not part of either first half or second half.

if [midnode != NULL] {

prev_of_slow_ptr->next = midnode;

midnode->next = second_half;

}

else

prev_of_slow_ptr->next = second_half;

}

return res;

}

/* Function to reverse the linked list Note that this

function may change the head */

void reverse[struct Node** head_ref]

{

struct Node* prev = NULL;

struct Node* current = *head_ref;

struct Node* next;

while [current != NULL] {

next = current->next;

current->next = prev;

prev = current;

current = next;

}

*head_ref = prev;

}

/* Function to check if two input lists have same data*/

bool compareLists[struct Node* head1, struct Node* head2]

{

struct Node* temp1 = head1;

struct Node* temp2 = head2;

while [temp1 && temp2] {

if [temp1->data == temp2->data] {

temp1 = temp1->next;

temp2 = temp2->next;

}

else

return 0;

}

/* Both are empty return 1*/

if [temp1 == NULL && temp2 == NULL]

return 1;

/* Will reach here when one is NULL

and other is not */

return 0;

}

/* Push a node to linked list. Note that this function

changes the head */

void push[struct Node** head_ref, char new_data]

{

/* allocate node */

struct Node* new_node = [struct Node*]malloc[sizeof[struct Node]];

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = [*head_ref];

/* move the head to pochar to the new node */

[*head_ref] = new_node;

}

// A utility function to print a given linked list

void printList[struct Node* ptr]

{

while [ptr != NULL] {

printf["%c->", ptr->data];

ptr = ptr->next;

}

printf["NULL\n"];

}

/* Driver program to test above function*/

int main[]

{

/* Start with the empty list */

struct Node* head = NULL;

char str[] = "abacaba";

int i;

for [i = 0; str[i] != '\0'; i++] {

push[&head, str[i]];

printList[head];

isPalindrome[head] ? printf["Is Palindrome\n\n"] : printf["Not Palindrome\n\n"];

}

return 0;

}

Java




/* Java program to check if linked list is palindrome */

class LinkedList {

Node head; // head of list

Node slow_ptr, fast_ptr, second_half;

/* Linked list Node*/

class Node {

char data;

Node next;

Node[char d]

{

data = d;

next = null;

}

}

/* Function to check if given linked list is

palindrome or not */

boolean isPalindrome[Node head]

{

slow_ptr = head;

fast_ptr = head;

Node prev_of_slow_ptr = head;

Node midnode = null; // To handle odd size list

boolean res = true; // initialize result

if [head != null && head.next != null] {

/* Get the middle of the list. Move slow_ptr by 1

and fast_ptr by 2, slow_ptr will have the middle

node */

while [fast_ptr != null && fast_ptr.next != null] {

fast_ptr = fast_ptr.next.next;

/*We need previous of the slow_ptr for

linked lists with odd elements */

prev_of_slow_ptr = slow_ptr;

slow_ptr = slow_ptr.next;

}

/* fast_ptr would become NULL when there are even elements

in the list and not NULL for odd elements. We need to skip

the middle node for odd case and store it somewhere so that

we can restore the original list */

if [fast_ptr != null] {

midnode = slow_ptr;

slow_ptr = slow_ptr.next;

}

// Now reverse the second half and compare it with first half

second_half = slow_ptr;

prev_of_slow_ptr.next = null; // NULL terminate first half

reverse[]; // Reverse the second half

res = compareLists[head, second_half]; // compare

/* Construct the original list back */

reverse[]; // Reverse the second half again

if [midnode != null] {

// If there was a mid node [odd size case] which

// was not part of either first half or second half.

prev_of_slow_ptr.next = midnode;

midnode.next = second_half;

}

else

prev_of_slow_ptr.next = second_half;

}

return res;

}

/* Function to reverse the linked list Note that this

function may change the head */

void reverse[]

{

Node prev = null;

Node current = second_half;

Node next;

while [current != null] {

next = current.next;

current.next = prev;

prev = current;

current = next;

}

second_half = prev;

}

/* Function to check if two input lists have same data*/

boolean compareLists[Node head1, Node head2]

{

Node temp1 = head1;

Node temp2 = head2;

while [temp1 != null && temp2 != null] {

if [temp1.data == temp2.data] {

temp1 = temp1.next;

temp2 = temp2.next;

}

else

return false;

}

/* Both are empty return 1*/

if [temp1 == null && temp2 == null]

return true;

/* Will reach here when one is NULL

and other is not */

return false;

}

/* Push a node to linked list. Note that this function

changes the head */

public void push[char new_data]

{

/* Allocate the Node &

Put in the data */

Node new_node = new Node[new_data];

/* link the old list off the new one */

new_node.next = head;

/* Move the head to point to new Node */

head = new_node;

}

// A utility function to print a given linked list

void printList[Node ptr]

{

while [ptr != null] {

System.out.print[ptr.data + "->"];

ptr = ptr.next;

}

System.out.println["NULL"];

}

/* Driver program to test the above functions */

public static void main[String[] args]

{

/* Start with the empty list */

LinkedList llist = new LinkedList[];

char str[] = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' };

String string = new String[str];

for [int i = 0; i < 7; i++] {

llist.push[str[i]];

llist.printList[llist.head];

if [llist.isPalindrome[llist.head] != false] {

System.out.println["Is Palindrome"];

System.out.println[""];

}

else {

System.out.println["Not Palindrome"];

System.out.println[""];

}

}

}

}

Python3




# Python3 program to check if

# linked list is palindrome

# Node class

class Node:

# Constructor to initialize

# the node object

def __init__[self, data]:

self.data = data

self.next = None

class LinkedList:

# Function to initialize head

def __init__[self]:

self.head = None

# Function to check if given

# linked list is palindrome or not

def isPalindrome[self, head]:

slow_ptr = head

fast_ptr = head

prev_of_slow_ptr = head

# To handle odd size list

midnode = None

# Initialize result

res = True

if [head != None and head.next != None]:

# Get the middle of the list.

# Move slow_ptr by 1 and

# fast_ptr by 2, slow_ptr

# will have the middle node

while [fast_ptr != None and

fast_ptr.next != None]:

# We need previous of the slow_ptr

# for linked lists with odd

# elements

fast_ptr = fast_ptr.next.next

prev_of_slow_ptr = slow_ptr

slow_ptr = slow_ptr.next

# fast_ptr would become NULL when

# there are even elements in the

# list and not NULL for odd elements.

# We need to skip the middle node for

# odd case and store it somewhere so

# that we can restore the original list

if [fast_ptr != None]:

midnode = slow_ptr

slow_ptr = slow_ptr.next

# Now reverse the second half

# and compare it with first half

second_half = slow_ptr

# NULL terminate first half

prev_of_slow_ptr.next = None

# Reverse the second half

second_half = self.reverse[second_half]

# Compare

res = self.compareLists[head, second_half]

# Construct the original list back

# Reverse the second half again

second_half = self.reverse[second_half]

if [midnode != None]:

# If there was a mid node [odd size

# case] which was not part of either

# first half or second half.

prev_of_slow_ptr.next = midnode

midnode.next = second_half

else:

prev_of_slow_ptr.next = second_half

return res

# Function to reverse the linked list

# Note that this function may change

# the head

def reverse[self, second_half]:

prev = None

current = second_half

next = None

while current != None:

next = current.next

current.next = prev

prev = current

current = next

second_half = prev

return second_half

# Function to check if two input

# lists have same data

def compareLists[self, head1, head2]:

temp1 = head1

temp2 = head2

while [temp1 and temp2]:

if [temp1.data == temp2.data]:

temp1 = temp1.next

temp2 = temp2.next

else:

return 0

# Both are empty return 1

if [temp1 == None and temp2 == None]:

return 1

# Will reach here when one is NULL

# and other is not

return 0

# Function to insert a new node

# at the beginning

def push[self, new_data]:

# Allocate the Node &

# Put in the data

new_node = Node[new_data]

# Link the old list off the new one

new_node.next = self.head

# Move the head to point to new Node

self.head = new_node

# A utility function to print

# a given linked list

def printList[self]:

temp = self.head

while[temp]:

print[temp.data, end = "->"]

temp = temp.next

print["NULL"]

# Driver code

if __name__ == '__main__':

l = LinkedList[]

s = [ 'a', 'b', 'a', 'c', 'a', 'b', 'a' ]

for i in range[7]:

l.push[s[i]]

l.printList[]

if [l.isPalindrome[l.head] != False]:

print["Is Palindrome\n"]

else:

print["Not Palindrome\n"]

print[]

# This code is contributed by MuskanKalra1

C#




/* C# program to check if linked list is palindrome */

using System;

class LinkedList {

Node head; // head of list

Node slow_ptr, fast_ptr, second_half;

/* Linked list Node*/

public class Node {

public char data;

public Node next;

public Node[char d]

{

data = d;

next = null;

}

}

/* Function to check if given linked list is

palindrome or not */

Boolean isPalindrome[Node head]

{

slow_ptr = head;

fast_ptr = head;

Node prev_of_slow_ptr = head;

Node midnode = null; // To handle odd size list

Boolean res = true; // initialize result

if [head != null && head.next != null] {

/* Get the middle of the list. Move slow_ptr by 1

and fast_ptr by 2, slow_ptr will have the middle

node */

while [fast_ptr != null && fast_ptr.next != null] {

fast_ptr = fast_ptr.next.next;

/*We need previous of the slow_ptr for

linked lists with odd elements */

prev_of_slow_ptr = slow_ptr;

slow_ptr = slow_ptr.next;

}

/* fast_ptr would become NULL when there are even elements

in the list and not NULL for odd elements. We need to skip

the middle node for odd case and store it somewhere so that

we can restore the original list */

if [fast_ptr != null] {

midnode = slow_ptr;

slow_ptr = slow_ptr.next;

}

// Now reverse the second half and compare it with first half

second_half = slow_ptr;

prev_of_slow_ptr.next = null; // NULL terminate first half

reverse[]; // Reverse the second half

res = compareLists[head, second_half]; // compare

/* Construct the original list back */

reverse[]; // Reverse the second half again

if [midnode != null] {

// If there was a mid node [odd size case] which

// was not part of either first half or second half.

prev_of_slow_ptr.next = midnode;

midnode.next = second_half;

}

else

prev_of_slow_ptr.next = second_half;

}

return res;

}

/* Function to reverse the linked list Note that this

function may change the head */

void reverse[]

{

Node prev = null;

Node current = second_half;

Node next;

while [current != null] {

next = current.next;

current.next = prev;

prev = current;

current = next;

}

second_half = prev;

}

/* Function to check if two input lists have same data*/

Boolean compareLists[Node head1, Node head2]

{

Node temp1 = head1;

Node temp2 = head2;

while [temp1 != null && temp2 != null] {

if [temp1.data == temp2.data] {

temp1 = temp1.next;

temp2 = temp2.next;

}

else

return false;

}

/* Both are empty return 1*/

if [temp1 == null && temp2 == null]

return true;

/* Will reach here when one is NULL

and other is not */

return false;

}

/* Push a node to linked list. Note that this function

changes the head */

public void push[char new_data]

{

/* Allocate the Node &

Put in the data */

Node new_node = new Node[new_data];

/* link the old list off the new one */

new_node.next = head;

/* Move the head to point to new Node */

head = new_node;

}

// A utility function to print a given linked list

void printList[Node ptr]

{

while [ptr != null] {

Console.Write[ptr.data + "->"];

ptr = ptr.next;

}

Console.WriteLine["NULL"];

}

/* Driver program to test the above functions */

public static void Main[String[] args]

{

/* Start with the empty list */

LinkedList llist = new LinkedList[];

char[] str = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' };

for [int i = 0; i < 7; i++] {

llist.push[str[i]];

llist.printList[llist.head];

if [llist.isPalindrome[llist.head] != false] {

Console.WriteLine["Is Palindrome"];

Console.WriteLine[""];

}

else {

Console.WriteLine["Not Palindrome"];

Console.WriteLine[""];

}

}

}

}

// This code is contributed by Arnab Kundu

Javascript




/* javascript program to check if linked list is palindrome */

var head; // head of list

var slow_ptr, fast_ptr, second_half;

/* Linked list Node */

class Node {

constructor[val] {

this.data = val;

this.next = null;

}

}

/*

* Function to check if given linked list is palindrome or not

*/

function isPalindrome[head] {

slow_ptr = head;

fast_ptr = head;

var prev_of_slow_ptr = head;

var midnode = null; // To handle odd size list

var res = true; // initialize result

if [head != null && head.next != null] {

/*

* Get the middle of the list. Move slow_ptr by 1 and fast_ptr by 2, slow_ptr

* will have the middle node

*/

while [fast_ptr != null && fast_ptr.next != null] {

fast_ptr = fast_ptr.next.next;

/*

* We need previous of the slow_ptr for linked lists with odd elements

*/

prev_of_slow_ptr = slow_ptr;

slow_ptr = slow_ptr.next;

}

/*

* fast_ptr would become NULL when there are even elements in the list and not

* NULL for odd elements. We need to skip the middle node for odd case and store

* it somewhere so that we can restore the original list

*/

if [fast_ptr != null] {

midnode = slow_ptr;

slow_ptr = slow_ptr.next;

}

// Now reverse the second half and compare it with first half

second_half = slow_ptr;

prev_of_slow_ptr.next = null; // NULL terminate first half

reverse[]; // Reverse the second half

res = compareLists[head, second_half]; // compare

/* Construct the original list back */

reverse[]; // Reverse the second half again

if [midnode != null] {

// If there was a mid node [odd size case] which

// was not part of either first half or second half.

prev_of_slow_ptr.next = midnode;

midnode.next = second_half;

} else

prev_of_slow_ptr.next = second_half;

}

return res;

}

/*

* Function to reverse the linked list Note that this function may change the

* head

*/

function reverse[] {

var prev = null;

var current = second_half;

var next;

while [current != null] {

next = current.next;

current.next = prev;

prev = current;

current = next;

}

second_half = prev;

}

/* Function to check if two input lists have same data */

function compareLists[head1, head2] {

var temp1 = head1;

var temp2 = head2;

while [temp1 != null && temp2 != null] {

if [temp1.data == temp2.data] {

temp1 = temp1.next;

temp2 = temp2.next;

} else

return false;

}

/* Both are empty return 1 */

if [temp1 == null && temp2 == null]

return true;

/*

* Will reach here when one is NULL and other is not

*/

return false;

}

/*

* Push a node to linked list. Note that this function changes the head

*/

function push[ new_data] {

/*

* Allocate the Node & Put in the data

*/

var new_node = new Node[new_data];

/* link the old list off the new one */

new_node.next = head;

/* Move the head to point to new Node */

head = new_node;

}

// A utility function to print a given linked list

function printList[ptr] {

while [ptr != null] {

document.write[ptr.data + "->"];

ptr = ptr.next;

}

document.write["NULL
"];

}

/* Driver program to test the above functions */

/* Start with the empty list */

var str = [ 'a', 'b', 'a', 'c', 'a', 'b', 'a' ];

var string = str.toString[];

for [i = 0; i < 7; i++] {

push[str[i]];

printList[head];

if [isPalindrome[head] != false] {

document.write["Is Palindrome"];

document.write["
"];

} else {

document.write["Not Palindrome"];

document.write["
"];

}

}

// This code contributed by gauravrajput1

Output:

a->NULL Is Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome

Time Complexity: O[n]
Auxiliary Space: O[1]

METHOD 3 [Using Recursion]
Use two pointers left and right. Move right and left using recursion and check for following in each recursive call.
1] Sub-list is a palindrome.
2] Value at current left and right are matching.

If both above conditions are true then return true.

The idea is to use function call stack as a container. Recursively traverse till the end of list. When we return from last NULL, we will be at the last node. The last node to be compared with first node of list.

In order to access first node of list, we need list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare [2, n-2] nodes. Again when recursion falls back to [n-2]nd node, we need reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.
However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.
Thanks to Sharad Chandra for suggesting this approach.

C++




// Recursive program to check if a given linked list is palindrome

#include

using namespace std;

/* Link list node */

struct node {

char data;

struct node* next;

};

// Initial parameters to this function are &head and head

bool isPalindromeUtil[struct node** left, struct node* right]

{

/* stop recursion when right becomes NULL */

if [right == NULL]

return true;

/* If sub-list is not palindrome then no need to

check for current left and right, return false */

bool isp = isPalindromeUtil[left, right->next];

if [isp == false]

return false;

/* Check values at current left and right */

bool isp1 = [right->data == [*left]->data];

/* Move left to next node */

*left = [*left]->next;

return isp1;

}

// A wrapper over isPalindromeUtil[]

bool isPalindrome[struct node* head]

{

isPalindromeUtil[&head, head];

}

/* Push a node to linked list. Note that this function

changes the head */

void push[struct node** head_ref, char new_data]

{

/* allocate node */

struct node* new_node = [struct node*]malloc[sizeof[struct node]];

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = [*head_ref];

/* move the head to point to the new node */

[*head_ref] = new_node;

}

// A utility function to print a given linked list

void printList[struct node* ptr]

{

while [ptr != NULL] {

cout data next;

}

cout data];

/* Move left to next node */

*left = [*left]->next;

return isp1;

}

// A wrapper over isPalindromeUtil[]

bool isPalindrome[struct node* head]

{

isPalindromeUtil[&head, head];

}

/* Push a node to linked list. Note that this function

changes the head */

void push[struct node** head_ref, char new_data]

{

/* allocate node */

struct node* new_node = [struct node*]malloc[sizeof[struct node]];

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = [*head_ref];

/* move the head to pochar to the new node */

[*head_ref] = new_node;

}

// A utility function to print a given linked list

void printList[struct node* ptr]

{

while [ptr != NULL] {

printf["%c->", ptr->data];

ptr = ptr->next;

}

printf["NULL\n"];

}

/* Driver program to test above function*/

int main[]

{

/* Start with the empty list */

struct node* head = NULL;

char str[] = "abacaba";

int i;

for [i = 0; str[i] != '\0'; i++] {

push[&head, str[i]];

printList[head];

isPalindrome[head] ? printf["Is Palindrome\n\n"] : printf["Not Palindrome\n\n"];

}

return 0;

}

Java




// Java program for the above approach

public class LinkedList{

// Head of the list

Node head;

Node left;

public class Node

{

public char data;

public Node next;

// Linked list node

public Node[char d]

{

data = d;

next = null;

}

}

// Initial parameters to this function are

// &head and head

boolean isPalindromeUtil[Node right]

{

left = head;

// Stop recursion when right becomes null

if [right == null]

return true;

// If sub-list is not palindrome then no need to

// check for the current left and right, return

// false

boolean isp = isPalindromeUtil[right.next];

if [isp == false]

return false;

// Check values at current left and right

boolean isp1 = [right.data == left.data];

left = left.next;

// Move left to next node;

return isp1;

}

// A wrapper over isPalindrome[Node head]

boolean isPalindrome[Node head]

{

boolean result = isPalindromeUtil[head];

return result;

}

// Push a node to linked list. Note that

// this function changes the head

public void push[char new_data]

{

// Allocate the node and put in the data

Node new_node = new Node[new_data];

// Link the old list off the the new one

new_node.next = head;

// Move the head to point to new node

head = new_node;

}

// A utility function to print a

// given linked list

void printList[Node ptr]

{

while [ptr != null]

{

System.out.print[ptr.data + "->"];

ptr = ptr.next;

}

System.out.println["Null"];

}

// Driver Code

public static void main[String[] args]

{

LinkedList llist = new LinkedList[];

char[] str = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' };

for[int i = 0; i < 7; i++]

{

llist.push[str[i]];

llist.printList[llist.head];

if [llist.isPalindrome[llist.head]]

{

System.out.println["Is Palindrome"];

System.out.println[""];

}

else

{

System.out.println["Not Palindrome"];

System.out.println[""];

}

}

}

}

// This code is contributed by abhinavjain194

Python3




# Python program for the above approach

# Head of the list

head = None

left = None

class Node:

def __init__[self, val]:

self.data = val

self.next = None

# Initial parameters to this function are

# &head and head

def isPalindromeUtil[right]:

global head, left

left = head

# Stop recursion when right becomes null

if [right == None]:

return True

# If sub-list is not palindrome then no need to

# check for the current left and right, return

# false

isp = isPalindromeUtil[right.next]

if [isp == False]:

return False

# Check values at current left and right

isp1 = [right.data == left.data]

left = left.next

# Move left to next node;

return isp1

# A wrapper over isPalindrome[Node head]

def isPalindrome[head]:

result = isPalindromeUtil[head]

return result

# Push a node to linked list. Note that

# this function changes the head

def push[new_data]:

global head

# Allocate the node and put in the data

new_node = Node[new_data]

# Link the old list off the the new one

new_node.next = head

# Move the head to point to new node

head = new_node

# A utility function to print a

# given linked list

def printList[ptr]:

while [ptr != None]:

print[ptr.data, end="->"]

ptr = ptr.next

print["Null "]

# Driver Code

str = ['a', 'b', 'a', 'c', 'a', 'b', 'a']

for i in range[0, 7]:

push[str[i]]

printList[head]

if [isPalindrome[head] and i != 0]:

print["Is Palindrome\n"]

else:

print["Not Palindrome\n"]

# This code is contributed by saurabh_jaiswal.

C#




/* C# program to check if linked list

is palindrome recursively */

using System;

public class LinkedList

{

Node head; // head of list

Node left;

/* Linked list Node*/

public class Node

{

public char data;

public Node next;

public Node[char d]

{

data = d;

next = null;

}

}

// Initial parameters to this function are &head and head

Boolean isPalindromeUtil[Node right]

{

left = head;

/* stop recursion when right becomes NULL */

if [right == null]

return true;

/* If sub-list is not palindrome then no need to

check for current left and right, return false */

Boolean isp = isPalindromeUtil[right.next];

if [isp == false]

return false;

/* Check values at current left and right */

Boolean isp1 = [right.data == [left].data];

/* Move left to next node */

left = left.next;

return isp1;

}

// A wrapper over isPalindromeUtil[]

Boolean isPalindrome[Node head]

{

Boolean result = isPalindromeUtil[head];

return result;

}

/* Push a node to linked list. Note that this function

changes the head */

public void push[char new_data]

{

/* Allocate the Node &

Put in the data */

Node new_node = new Node[new_data];

/* link the old list off the new one */

new_node.next = head;

/* Move the head to point to new Node */

head = new_node;

}

// A utility function to print a given linked list

void printList[Node ptr]

{

while [ptr != null]

{

Console.Write[ptr.data + "->"];

ptr = ptr.next;

}

Console.WriteLine["NULL"];

}

/* Driver code */

public static void Main[String[] args]

{

/* Start with the empty list */

LinkedList llist = new LinkedList[];

char []str = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' };

//String string = new String[str];

for [int i = 0; i < 7; i++] {

llist.push[str[i]];

llist.printList[llist.head];

if [llist.isPalindrome[llist.head] != false]

{

Console.WriteLine["Is Palindrome"];

Console.WriteLine[""];

}

else

{

Console.WriteLine["Not Palindrome"];

Console.WriteLine[""];

}

}

}

}

// This code is contributed by Rajput-Ji

Javascript




// javascript program for the above approach

// Head of the list

var head;

var left;

class Node {

constructor[val] {

this.data = val;

this.next = null;

}

}

// Initial parameters to this function are

// &head and head

function isPalindromeUtil[ right] {

left = head;

// Stop recursion when right becomes null

if [right == null]

return true;

// If sub-list is not palindrome then no need to

// check for the current left and right, return

// false

var isp = isPalindromeUtil[right.next];

if [isp == false]

return false;

// Check values at current left and right

var isp1 = [right.data == left.data];

left = left.next;

// Move left to next node;

return isp1;

}

// A wrapper over isPalindrome[Node head]

function isPalindrome[ head] {

var result = isPalindromeUtil[head];

return result;

}

// Push a node to linked list. Note that

// this function changes the head

function push[ new_data] {

// Allocate the node and put in the data

var new_node = new Node[new_data];

// Link the old list off the the new one

new_node.next = head;

// Move the head to point to new node

head = new_node;

}

// A utility function to print a

// given linked list

function printList[ ptr] {

while [ptr != null] {

document.write[ptr.data + "->"];

ptr = ptr.next;

}

document.write["Null "];

document.write["
"];

}

// Driver Code

var str = [ 'a', 'b', 'a', 'c', 'a', 'b', 'a' ];

for [var i = 0; i < 7; i++] {

push[str[i]];

printList[head];

if [isPalindrome[head]] {

document.write["Is Palindrome"];

document.write["
"];

document.write["
"];

} else {

document.write["Not Palindrome"];

document.write["
"];

document.write["
"];

}

}

// This code contributed by aashish2995

Output:

a->NULL Not Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome

Time Complexity: O[n]
Auxiliary Space: O[n] if Function Call Stack size is considered, otherwise O[1].




Article Tags :

Linked List

Accolite

Adobe

Amazon

KLA Tencor

Kritikal Solutions

Microsoft

palindrome

Snapdeal

Yodlee Infotech

Practice Tags :

Accolite

Amazon

Microsoft

Snapdeal

Adobe

Yodlee Infotech

KLA Tencor

Kritikal Solutions

Linked List

palindrome

Read Full Article

Palindrome Linked List in Python

PythonServer Side ProgrammingProgramming

Suppose we have a linked list. We have to check whether the list elements are forming a palindrome or not. So if the list element is like [1,2,3,2,1], then this is a palindrome.

To solve this, we will follow these steps −

  • fast := head, slow := head, rev := None and flag := 1

  • if the head is empty, then return true

  • while fast and next of fast is available

    • if next of the next of fast is available, then set flag := 0 and break the loop

    • fast := next of the next of fast

    • temp := slow, slow := next of slow

    • next of temp := rev, and rev := temp

  • fast := next of slow, and next of slow := rev

  • if flag is set, then slow := next of slow

  • while fast and slow are not None,

    • if the value of fast is not the same as the value of slow, then return false

    • fast := next of fast, and slow := next of slow

  • return true

C


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

#include

#include

// A Linked List Node

struct Node

{

int data;

struct Node* next;

};

// Helper function to create a new node with the given data and

// pushes it onto the list's front

void push[struct Node** head, int data]

{

// create a new linked list node from the heap

struct Node* newNode = [struct Node*]malloc[sizeof[struct Node]];

newNode->data = data;

newNode->next = *head;

*head = newNode;

}

// Recursive function to check if the linked list is a palindrome or not

int checkPalindrome[struct Node** left, struct Node* right]

{

// base case

if [right == NULL] {

return 1;

}

int result = checkPalindrome[left, right->next] && [[*left]->data == right->data];

[*left] = [*left]->next;

return result;

}

// Function to check if the linked list is a palindrome or not

int checkPalin[struct Node* head] {

return checkPalindrome[&head, head];

}

int main[void]

{

// input keys

int keys[] = { 1, 3, 5, 3, 1};

int n = sizeof[keys] / sizeof[keys[0]];

struct Node* head = NULL;

for [int i = n - 1; i >= 0; i--] {

push[&head, keys[i]];

}

if [checkPalin[head]] {

printf["The linked list is a palindrome"];

}

else {

printf["The linked list is not a palindrome"];

}

return 0;

}

DownloadRun Code

Output:

The linked list is a palindrome

Palindrome LinkedList — Day 2[Python]

Photo by Zulmaury Saavedra on Unsplash

Today is my second day at the 365 days of coding challenge. I will be solving a question based on the LinkedList. Before I dive into the question let me talk about a few features of LinkedList.

  1. A LinkedList contains a sequence of nodes that are connected to each other using a pointer to the following nodes.

Singly LinkedList

2. A basic node will contain 2 parts,

a. Data

b. Address for next pointer

3. A LinkedList has a head pointer that points towards the start of the LinkedList.

4. A LinkedList does not necessarily have a contiguous memory allocation.

The below code shows the structure of a node on a LinkedList.

class Node:
def __init__[self, data]:
self.data = data
self.next = None

Okay, now that we have seen about LinkedList lets move on to today's question.

234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

My first thought after seeing this question was to use a stack, insert data from each node into the stack, and then compare elements by popping elements from the stack and each element in the linked list.

The code would look like the following

class Solution:
def insert_stack[self, head]:
stack_rev = []
while[head]:
stack_rev.append[head.val]
head = head.next
return stack_rev

def isPalindrome[self, head: ListNode] -> bool:
if head == None:
return True
stack_rev = self.insert_stack[head]
while[head]:
if[head.val == stack_rev.pop[]]:
head = head.next
else:
return False
return True

Complexity analysis

Time Complexity

We would be required to traverse through each of the element in LinkedList and that would take O[N] time

Space Complexity

We are using a stack to store the elements which will take up O[N] space.

Can we try reducing space usage?

Maybe if we divide our LinkedList in the middle, reverse the first half and then compare the nodes in both the half.

class Solution:
def isPalindrome[self, head]:
rev = None
# Slow pointer
slow = head
# Fast pointer
fast = head
# Until the first half keep reversing the nodes
while fast and fast.next:
#Keep moving in double speed
fast = fast.next.next
#Keep reversing the node
slow_next = slow.next
slow.next = rev
rev = slow
slow = slow_next
#In case lenght of linkedlist is odd
if fast:
slow = slow.next
# Compare the elements
while rev and rev.val == slow.val:
slow = slow.next
rev = rev.next
return not rev

Complexity analysis

Time Complexity

We would be required to traverse through each of the element in LinkedList and that would take O[N] time

Space Complexity

We are not using any extra space in order to perform the above transformation and hence the space used is O[1].

I would like to improve my writing skills so any suggestions or critiques are highly welcomed.

Checking if a linked list is a palindrome

A number is a palindrome if it reads the same forwards as it does backward. For example, the number 123332112333211233321 is a palindrome.

Linked lists can also be palindromes if they have the same order of elements when traversed forwards and backward​.

Program to determine whether a singly linked list is the palindrome

Explanation

In this program, we need to check whether given singly linked list is a palindrome or not. A palindromic list is the one which is equivalent to the reverse of itself.

The list given in the above figure is a palindrome since it is equivalent to its reverse list, i.e., 1, 2, 3, 2, 1. To check whether a list is a palindrome, we traverse the list and check if any element from the starting half doesn't match with any element from the ending half, then we set the variable flag to false and break the loop.

In the last, if the flag is false, then the list is palindrome otherwise not. The algorithm to check whether a list is a palindrome or not is given below.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class Palindrome which has three attributes: head, tail, and size.
  3. addNode[] will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.
  4. reverseList[] will reverse the order of the node present in the list:
    1. Node current will represent a node from which a list needs to be reversed.
    2. Node prevNode represent the previous node to current and nextNode represent the node next to current.
    3. The list will be reversed by swapping the prevNode with nextNode for each node.
  5. isPalindrome[] will check whether given list is palindrome or not:
    1. Declare a node current which will initially point to head node.
    2. The variable flag will store a boolean value true.
    3. Calculate the mid-point of the list by dividing the size of the list by 2.
    4. Traverse through the list till current points to the middle node.
    5. Reverse the list after the middle node until the last node using reverseList[]. This list will be the second half of the list.
    6. Now, compare nodes of first half and second half of the list.
    7. If any of the nodes don't match then, set a flag to false and break the loop.
    8. If the flag is true after the loop which denotes that list is a palindrome.
    9. If the flag is false, then the list is not a palindrome.
  6. display[] will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

Nodes of the singly linked list: 1 2 3 2 1 Given singly linked list is a palindrome

C

Output:

Nodes of the singly linked list: 1 2 3 2 1 Given singly linked list is a palindrome

JAVA

Output:

Nodes of singly linked list: 1 2 3 2 1 Given singly linked list is a palindrome

C#

Output:

Nodes of singly linked list: 1 2 3 2 1 Given singly linked list is a palindrome

PHP

Output:

Nodes of singly linked list: 1 2 3 2 1 Given singly linked list is a palindrome

Video liên quan

Bài mới nhất

Chủ Đề