LeetCode | 234. 回文链表
- 这里的解法是先找到中间结点
- 然后再将中间节点后面的节点逆序一下
- 然后再从头开始和从中间开始挨个比较
- 如果中间开始的指针到走最后都相等,就返回
true
,否则返回false
代码如下:
struct ListNode* reverseList(struct ListNode* head) { struct ListNode* n1,*n2,*n3; if(head == NULL) return NULL; n1 = NULL,n2 = head;n3 = n2->next; while(n2) { n2->next = n1; n1 = n2; n2 = n3; if(n3) n3 = n3->next; } return n1; } struct ListNode* middleNode(struct ListNode* head) { struct ListNode* slow = head,*fast = head; while(slow && slow->next) { slow = slow->next->next; fast = fast->next; } return fast; } bool isPalindrome(struct ListNode* head) { struct ListNode* mid = middleNode(head); struct ListNode* rhead = reverseList(mid); while(head&&rhead) { if(head->val == rhead->val) { head = head->next; rhead = rhead->next; } else { return false; } } return true; }