当前位置:   article > 正文

单链表练习题:判断链表是不是回文链表_c语言数据结构判断单链表是否回文

c语言数据结构判断单链表是否回文

思路:找到链表的中间节点,然后逆置后半段,再从两边比较对应位置是否值域相等。
在这里插入图片描述
在这里插入图片描述
代码:

public boolean chkPalindrome(){
if(head==null){
return false;
}
if(head.next==null){
return true;
}
Node fast=head;
Node cur=head;
//找到中间节点
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
Node cur=slow.next;
//逆置后半段
while(cur!=null){
Node curNext=cur.next;
cur.next=slow;
slow=cur;
cur=curNext;
}
while(head!=slow){
if(head.data!=slow.data){
return false;
}
if(head.next==slow){
return true;
}
head=head.next;
slow=slow.next;
}
return true;
}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/612050
推荐阅读
相关标签
  

闽ICP备14008679号