234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could do it in O (n) time and O (1) space?
Main topic:
Determine whether a single-linked list is a palindrome list.
Ideas:
Find the nodes in the middle of the list, divide the list from the middle into 2 parts, the right half to reverse the list, and then compare the left half with the inverted right-half list. to produce results.
/** * 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) //chain list reversal { 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--; } &nBsp; 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; }};
Reviewed the method of single-linked list inversion.
2016-08-12 20:17:23
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1837428
Leetcode 234. Palindrome Linked List Link list