Given a singly linked list, determine if it is a palindrome.
思路:
用快慢指针找到链表中点,反转后半部分链表,然后与前半部分进行匹配,随后将链表恢复原状(本题没有这个要求,具体情况具体对待)。
C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 12 ListNode* reverseList(ListNode *listHead) 13 { 14 ListNode *preNode = NULL; 15 ListNode *curNode = listHead; 16 ListNode *reverseHead = NULL; 17 18 while(curNode != NULL) 19 { 20 ListNode *nextNode = curNode->next; 21 22 if(nextNode == NULL) 23 { 24 reverseHead = curNode; 25 } 26 27 curNode->next = preNode; 28 preNode = curNode; 29 curNode = nextNode; 30 } 31 32 return reverseHead; 33 } 34 35 bool isPalindrome(ListNode* head) { 36 37 if(head == 0 || head->next == 0) 38 return true; 39 40 ListNode *p1 = head; 41 ListNode *p2 = head; 42 while(p2->next != 0 && p2->next->next != 0) 43 { 44 p1 = p1->next; 45 p2 = p2->next->next; 46 } 47 48 ListNode *rhead = reverseList(p1->next); 49 p1->next = 0; 50 51 p1 = head; 52 p2 = rhead; 53 while(p2 != 0) 54 { 55 if(p2->val != p1->val) 56 return false; 57 58 p1 = p1->next; 59 p2 = p2->next; 60 } 61 62 p1 = head; 63 while(p1->next != 0) 64 p1 = p1->next; 65 66 ListNode *mhead = reverseList(rhead); 67 p1->next = mhead; 68 69 return true; 70 } 71 };
时间: 2024-10-29 12:27:37