LeetCode6:回文链表

回文链表

题目描述

请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true

方法1.

执行步骤:
第一步:找到中间的那个节点
第二步:从中间那个链表往后依次进行翻转,
第三步:将翻折之后的与前面一半的链表数据进行比较(只要有一个数据不一样那么就是错误的)

bool isPalindrome(struct ListNode* head){
struct ListNode* fast,*slow;
    if (head == NULL || head->next == NULL) {
      return true;
    }
    //找到了中间结点 return slow就是中间结点
    fast=slow=head;
    while (fast && fast->next) {
    slow=slow->next;
    fast=fast->next->next;
    }
 struct ListNode* cur,*newH,*next;  
  newH=NULL;
  cur=slow;
while (cur) {
 next=cur->next;
 cur->next=newH;
 newH=cur;
 //更新链表
 cur=next; 
}
cur=newH;
while(head && cur) {
  if (head->val != cur->val) {
  return false;
  } else {
  head=head->next;
  cur=cur->next;
  }
}
  return true;
}

方法2:常规法 将链表转化成数组

第一步:将链表依次放入到新创建的数组中
第二步:依次进行比较放入的元素

 bool isPalindrome(struct ListNode* head){
      struct ListNode* cur;
      int idx=0;
      int arr[1000000]={0};
      cur=head;
     while(cur) {
    arr[idx++]=cur->val;
      cur=cur->next;  
     }
        int start=0;
        int end=idx-1;
    while (start < end) {
        if(arr[start] != arr[end]) 
        return false;
        start++;
        end--;
    }
    return true;
 }

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值