1. Description of the problem
Given a single linked list, it is inferred that the content is not a palindrome type.
Like 1–>2–>3–>2–>1. The time and space complexity are as low as possible.
2. Methods and Ideas
1) a relatively simple algorithm.
Because a given data structure is a single-linked list, to access the trailing elements of a linked list, you must start from the beginning. To facilitate inference. We can apply for a secondary stack structure to store the contents of the linked list, the first traversal of the linked list node values sequentially into the stack, the second traversal is more inference is a palindrome.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */classSolution { Public:BOOLIspalindrome (listnode* head) {if(head = = NULL | | head->next = = NULL)return true; Stack<int>St ListNode *tmp = head; while(TMP) {St.push (tmp->val); TMP = tmp->next; } while(head) {if(Head->val! = St.top ())return false; Head = head->next; St.pop (); }return true; }};
2). Time O (n) and Space O (1) solution
Since the use of the stack, can think of the recursive process itself is the process of entering and exiting the stack, we can first recursive access to the single linked list, and then do the comparison. This eliminates the auxiliary space, thus reducing the space complexity to O (1). The code is as follows:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */Class Solution {Private: ListNode *lst; Public: boolJudge(ListNode *head) {if(head = = NULL)return true;if(judge (head->next) = =false)return false;if(Lst->val! = head->val)return false;Else{LST = lst->next;return true; }} bool Ispalindrome (listnode* head) {if(head = = NULL | | head->next = = NULL)return true; LST = head;returnJudge (head); }};
Leetcode 234 palindrome Linked List complexity is time O (n) and Space (1) Solution