leetcode206
反转一个单链表。
class Solution
{
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = NULL, *pre = head;
while (pre != NULL) {
ListNode* t = pre->next;
pre->next = cur;
cur = pre;
pre = t;
}
return cur;
}
};
比较常见的思路,利用双指针,一个在前,一个在后,进行就地翻转
如果说便于理解的话,其实还可以写出一种三指针的就地翻转格式,就不写了
第二个方法:头插法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *p,*q;
ListNode *t= new ListNode(1); //t作头结点
p=head;
t->next=NULL;
while(p) {
q=p;
p=p->next;
q->next=t->next;
t->next=q;
}
head=q;
return head;
}
};
第三种,递归法,理解一下
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* ret = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return ret;
}
};
leetcode234
请判断一个链表是否为回文链表。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head)
return true;
if(!head->next)
return true;
vector<int> record;
ListNode* first = head;
while(first){
record.push_back(first->val);
first = first->next;
}
int left = 0, right = record.size() - 1;
while(left < right){
if(record[left] != record[right])
return false;
left++;
right--;
}
return true;
}
};
利用了一个辅助数组,这个肯定是最好想到了的
题目中问能不能限制一下时间和空间复杂度,思考一下
class Solution {
public: //题解:快慢指针法,快指针走两步,慢指针走一步,找到链表的中点。然后,翻转后半部分。最后从头、中点开始判断是否相同。
bool isPalindrome(ListNode* head) {
if(!head||!head->next)return true;
ListNode *fast=head,*slow=head,*pre=nullptr; //1、找到链表的中点,链表长度奇偶不影响
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
} //2、将slow之后链表进行断开且反转,最后翻转完成之后pre指向反转链表的头节点
while(slow){
ListNode *p=slow->next;
slow->next=pre;
pre=slow;
slow=p;
} //3、前后链表进行比较,注意若为奇数链表,后半部分回比前部分多1一个节点,然而我们只比较相同长度的节点值,巧妙地避开这点判断
while(head&&pre){
if(head->val!=pre->val)return false;
head=head->next;
pre=pre->next;
}
return true;
}
};
快慢指针找到链表的中点,然后翻转后半段再进行判断,very very nice
leetcode237
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* del=node->next;
node->val=node->next->val; //使当前节点的val值为下一个节点的val值
node->next=node->next->next; //使当前节点指向下下个节点
delete del;
}
};
很简单的一个题,但是感觉题目描述有点问题,迷茫