/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param head ListNode类 the head * @return bool布尔型 */ //增加结点 struct ListNode* BuyNode(int x) { struct ListNode*newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); newnode->val=x; newnode->next=NULL; return newnode; } struct ListNode* CopyList(struct ListNode* plist) { struct ListNode* cur=plist; struct ListNode* copy1=BuyNode(0); struct ListNode* head2=copy1; while(cur != NULL) { struct ListNode* copy=BuyNode(cur->val); cur=cur->next; copy1->next=copy; copy1=copy1->next; } return head2->next; } //反转链表 struct ListNode* ExchangeList(struct ListNode* plist) { struct ListNode* pre=NULL; struct ListNode* cur=plist; while(cur != NULL) { struct ListNode* tmp=cur->next; cur->next=pre; pre=cur; cur=tmp; } return pre; } bool isPail(struct ListNode* head ) { //判断链表中元素的个数 struct ListNode* cur=head; int size=0; while(cur != NULL) { size++; cur=cur->next; } //判断是否为空或只有一个 if(head == NULL || size==1) { return head; } //将链表head拷贝到tmp struct ListNode* head2=CopyList(head); //反转链表 struct ListNode* head3=ExchangeList(head); //比较 while(head3 && head2) { if(head3->val != head2->val) { return false; } head3=head3->next; head2=head2->next; } return true; }