【面试题-链表】单向链表元素是否回文,要求空间复杂度O(1)

题目如题

单向链表元素是否回文,要求空间复杂度O(1)

思路:

先遍历一次链表得到链表长度。

第二次遍历到链表中间,并在遍历的时候进行逆转。

然后两个指针分离,分别向两个端点移动,同时进行比较,数据相同则继续,数据不同则直接返回false。直到遍历完成,最后返回true。

【代码】

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int w;
    node *next;
};
bool ok(node *head)
{
    int len=0;
    node *it=head;
    while(it!=NULL) len++,it=it->next;
    //printf("len:%d\n",len);

    node *it1=new node();
    for(int i=1;i<=len/2;++i){
        node *ne=head->next;
        head->next=it1->next;
        it1->next=head;
        head=ne;
    }
    if(len%2) head=head->next;
    it1=it1->next;

      while(it1!=NULL) {
          if(it1->w!=head->w) return 0;
          it1=it1->next;
          head=head->next;
      }
      return 1;

}
int main()
{
    node *head,*p;
    head=new node();
    p=head;
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;++i){
        node *ne=new node();
        int x;
        scanf("%d",&x);
        ne->w=x;
        p->next=ne;
        p=p->next;
    }

    printf("%d\n",ok(head->next));
}
/*
6
1 2 3 3 2 1
*/

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/106949681