Palindrome Linked List
Head insertion (头插法) to create new List
需要一个变量来保存历史最新头节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// head insertion
ListNode* inverseList(ListNode* head)
{
ListNode *curr = head;
ListNode *temp = NULL;
while(curr != NULL)
{
ListNode *node = new ListNode(curr->val);
node -> next = temp;
temp = node;
curr = curr->next;
}
return temp;
}
bool isPalindrome(ListNode* head) {
ListNode *newhead = inverseList(head);
while(head != NULL && newhead != NULL)
{
if(head->val != newhead->val)
return false;
head = head->next;
newhead = newhead ->next;
}
return true;
}
};
Tail insertion(尾插法)
需要一个变量保存头节点和另一个变量保存当前最后一个节点