本文共 2401 字,大约阅读时间需要 8 分钟。
b,每一次将head插入到 节点 t 和节点 q之间,更新head和q,t保持不变
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool isPalindrome(ListNode* head) { if (head == NULL){ return true; } // find length of list int lenList = 1; ListNode* cursor = head; while (cursor->next != NULL){ cursor = cursor->next; lenList ++; } if (lenList == 1){ return true; } // get pointer to tail of list ListNode* curTail = cursor; // get pointer to middle of list int midIndex = lenList/2 + lenList % 2 - 1; ListNode* curMid = head; while (midIndex != 0){ curMid = curMid->next; midIndex --; } // reverse the last half of list ListNode * mutableTail = curTail->next; // point to tail->next always ListNode * temp = NULL; // point to curMid->next always while (curMid->next != curTail){ temp = curMid->next; curMid->next = temp->next; curTail->next = temp; temp->next = mutableTail; mutableTail = curTail->next; } ListNode * curHeaderStart = head; ListNode * curMidStart = curMid->next; while (curMidStart != NULL){ if (curHeaderStart->val != curMidStart->val) return false; curHeaderStart = curHeaderStart->next; curMidStart = curMidStart->next; } return true; }};
转载地址:http://ecpbb.baihongyu.com/