Problem 234. Palindrome Linked List
-
题目描述
Given a singly linked list, determine if it is a palindrome.Example:
Input: 1->2->2->1 Output: true
-
解题思路
要判断一个链表是否是回文链表,且要求时间复杂度和空间复杂度分别为 O(n) 和 O(1)。一个可行的办法是:
- 利用快慢指针 fast 和 slow,fast 每次向前移动两步,slow 每次向前移动一步,当 fast 指向NULL 时,slow 所在的节点即为链表的中间节点。
- 以 slow 为起始节点,对 slow 后面的链表进行翻转,翻转结束之后将前后链表断开;
- 令 left 表示前链表,right 表示后链表,则同时遍历 left 和 right,判断 left 和 right 的每一个节点的值是否相等,只要出现不相等的情况则原始链表不是回文链表。
- 代码实现
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL)
return true;
ListNode * fast = head, * slow = head, * middle_pre = head;
//找到中间节点
while(fast != NULL && fast->next != NULL){
middle_pre = slow;
slow = slow->next;
fast = fast->next->next;
}
//翻转后半部分,将前后链表断开
ListNode * cur = middle_pre->next;
ListNode * cur_pre = NULL;
ListNode * cur_next = NULL;
while(cur->next != NULL){
cur_next = cur->next;
cur->next = cur_pre;
cur_pre = cur;
cur = cur_next;
}
cur->next = cur_pre;
middle_pre->next = NULL;
//遍历前后链表
ListNode* left = head, *right = cur;
while(left != NULL && right != NULL){
if(left->val != right->val)
return false;
left = left->next;
right = right->next;
}
return true;
}
};
Problem 237. Delete Node in a Linked List
-
题目描述
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.Example:
Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
-
解题思路
本题的意思是,在只传入链表的某个节点的情况下,如何将该节点从链表中删除?一种简单但独特的思路是:找到该节点 node 的下一个节点 temp,并将 temp 的值赋值给 node,随后删除节点temp 即可(即为传入的节点 node 找到一个替身)。 -
代码实现
class Solution {
public:
void deleteNode(ListNode* node) {
if(node == NULL || node->next == NULL)
return;
ListNode* cur = node, *temp = node->next;
cur->val = temp->val;
cur->next = temp->next;
delete temp;
}
};