题目链接
解析:
完整代码:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class PalindromeList { public: bool chkPalindrome(ListNode* A) { // write code here ListNode* pcur = A; int i = 0; int arr [900] = {0}; //将链表中的值存放到数组中 while ( pcur ) { arr[ i++ ] = pcur -> val; pcur = pcur -> next; } int left = 0; int right = i - 1; // i 表示的是数组中有效的元素个数, i - 1 代表下标 while ( left < right ) { if ( arr [left] != arr [right]) return false; left++; right--; } //跳出循环,表示 left 和 right 相等,此时就是回文结构 return true; } };注意:
上面的代码仅限于在牛客网,放在力扣上就不行了,因为在牛客网明确指出了链表的长度,此时就可以取巧将数组的大小规定为900
力扣的相同题目链接
解析:
完整代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: //找中间节点 ListNode* midNode(ListNode* head) { ListNode* slow,*fast; slow = fast = head; while( fast && fast -> next) { slow = slow -> next; fast = fast -> next -> next; } return slow; } //反转链表 ListNode* reverseListNode(ListNode* head) { if(head == NULL) return NULL; ListNode* n1,*n2,*n3; n1 = NULL, n2 = head, n3 = n2->next; while(n2) { n2->next = n1; n1 = n2; n2 = n3; if(n3) n3 = n3->next; } return n1; } bool isPalindrome(ListNode* head) { //1、找中间节点 ListNode* mid = midNode(head); //2、反转以中间节点为头的链表 ListNode* ret = reverseListNode(mid); //3、遍历两个链表,两个指针比较,循环结束条件:right = NULL ListNode* left,*right; left = head,right = ret; while( right ) { if( left ->val != right ->val) return false; left = left->next; right = right ->next; } //跳出循环,相等——回文结构 return true; } };思路3用的就是多个方法的集合