标签:链表
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?
题目大意:
判断一个单链表是否为回文链表。
思路:
找到链表中间的节点,将链表从中间分为2部分,右半部分进行链表反向转换,然后左半部分和反转后的右半部分链表进行比较。得出结果。
代码如下:
/** * 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) //链表反转 { 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; } };
复习了单链表反转的方法。
2016-08-12 20:17:23
本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1837428
leetCode 234. Palindrome Linked List 链表
标签:链表
原文地址:http://qiaopeng688.blog.51cto.com/3572484/1837428