您好,登錄后才能下訂單哦!
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
題目大意:
判斷一個(gè)單鏈表是否為回文鏈表。
思路:
找到鏈表中間的節(jié)點(diǎn),將鏈表從中間分為2部分,右半部分進(jìn)行鏈表反向轉(zhuǎn)換,然后左半部分和反轉(zhuǎn)后的右半部分鏈表進(jìn)行比較。得出結(jié)果。
代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode * reverseList(ListNode *head) //鏈表反轉(zhuǎn) { ListNode *pre,*next; pre = NULL; next = NULL; while(head) { next = head->next; head->next = pre; pre = head; head = next; } return pre; } bool isPalindrome(ListNode* head) { if( NULL == head || NULL == head->next) return true; int len = 0; ListNode *p = head; while(p) { len++; p = p->next; } ListNode * rightListHead; rightListHead = head; int leftLen = len / 2; int rightLen = len - leftLen; int i = leftLen; while(i) { rightListHead = rightListHead->next; i--; } rightListHead = reverseList(rightListHead); ListNode * left = head; ListNode * right = rightListHead; while(i < leftLen) { if(left->val == right->val) { left = left->next; right = right->next; } else { return false; } i++; } return true; } };
復(fù)習(xí)了單鏈表反轉(zhuǎn)的方法。
2016-08-12 20:17:23
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。