所以我想找出链表中是否存在回文,并打印该值。但是问题是即时通讯使用长整型值,并且想要在节点内甚至跨节点查找回文。即给定的列表:123-> 32166-> 78-> 1222最长的披肩应该是:123321我已经尝试了很多事情,但我似乎无法理解该怎么做。好的,如果您不显示任何代码,但是我很想听听解决此问题的任何想法。我有一些想法:将节点放入数组中,然后尝试在其中找到一个花环(尽管会占用大量内存)-反转列表并进行比较,但是存在每个节点中具有不同大小的整数值的问题即将78与32166进行比较将是不明智的-在尾部和头部分别创建两个指针,如果两个值都为true,则一个一个地移动,但这也有很多问题。
某些代码:
int palindrome()
{
// node *prev,*cur,*next;
// cur=head;
// prev=next=NULL;
list obj1;
node *s,*e;
s=obj1.head;
e=head;
while(s && e)
{
while(s->data==e->data)
{
e=e->next;
s=s->next;
cout<<"\n\n\n"<<e->data<<s->data;
}
if(s->data!=e->data)
{
e=e->next;
}
}
}
您不必使用LinkedList。试试这个解决方案,归功于GeeksforGeeks:
// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
#include <bits/stdc++.h>
using namespace std;
// A utility function to print a substring str[low..high]
void printSubStr(char* str, int low, int high)
{
for( int i = low; i <= high; ++i )
cout << str[i];
}
// This function prints the longest palindrome substring (LPS)
// of str[]. It also returns the length of the longest palindrome
int longestPalSubstr(char *str)
{
int maxLength = 1; // The result (length of LPS)
int start = 0;
int len = strlen(str);
int low, high;
// One by one consider every character as center point of
// even and length palindromes
for (int i = 1; i < len; ++i)
{
// Find the longest even length palindrome
// with center points as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len && str[low] == str[high])
{
if (high - low + 1 > maxLength)
{
start = low;
maxLength = high - low + 1;
}
--low;
++high;
}
// Find the longest odd length palindrome with center
// point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len && str[low] == str[high])
{
if (high - low + 1 > maxLength)
{
start = low;
maxLength = high - low + 1;
}
--low;
++high;
}
}
cout<<"Longest palindrome substring is: ";
printSubStr(str, start, start + maxLength - 1);
return maxLength;
}
// Driver program to test above functions
int main()
{
char str[] = "forgeeksskeegfor";
cout<<"\nLength is: "<<longestPalSubstr(str)<<endl;
return 0;
}