1. Description of the problem
Given a single linked list, it is judged that the content is not a palindrome type. such as 1–>2–>3–>2–>1. The time and space complexity are as low as possible.
2. Methods and Ideas
1) relatively simple algorithm.
Since the given data structure is a single-linked list, to access the trailing elements of the linked list, you must traverse from the beginning. For the convenience of judgment, 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 comparison to determine whether it 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, you can think of the recursive process itself is the process of entering and exiting the stack, we can first recursively access 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); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 234 palindrome Linked List complexity of Time O (n) and Space (1) solution