我写了一段代码来检查单向链表是否是回文。我做了两个步骤:如何检查链接列表是回文还是不是Java?
1st。反转原始链接列表。
2nd。检查原始链接列表和反向链接列表是否具有相同的元素。
public static Boolean isPalindrome(Node input){
Node reversed= reverse(input);
while (input!=null){
if(input.item!=reversed.item)
return false;
input=input.next;
reversed=reversed.next;
}
return true;
}
static Node head;
public static Node reverse(Node input){
if(input==null || input.next==null){
head=input;
return input;
}
else{
reverse(input.next);
input.next.next=input;
input.next=null;
return head;
}
}
该程序的工作原理。但我认为,当执行反向方法时,由于原始链表的头部被传入,所以原始链表也可能发生改变,所以isPalindrome也应该返回true,对吗?我是对的还是可以告诉我,我是否误解了任何概念?感谢
这是最主要的功能以及如何使用这些代码:
public static void main(String [] args){
Node a=new Node(9);
Node b=new Node(8);
Node c=new Node(7);
Node d=new Node(6);
a.next=b;
b.next=c;
c.next=d;
//d.next=c;
Boolean tf=isPalindrome(a);
if (tf)
System.out.println("Is Palindrome!");
else
System.out.println("Not Palindrome");
}
您能否提供显示如何调用这些方法的代码? –
嗯,当然。我只是使用print子句:Boolean tf = isPalindrome(a); \t \t if(tf) \t \t \t System.out.println(“Is Palindrome!”); \t \t else \t \t \t System.out.println(“Not Palindrome”); –