83. 删除排序链表中的重复元素
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head||!head->next) return head;//!!每次都不加边界条件啊啊啊啊啊!
ListNode* p=head;
while(p&&p->next){
if(p->val==p->next->val){p->next=p->next->next;}
else p=p->next;
}
return head;
}
};
141. 环形链表
//快慢指针的用法
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head||!head->next) return false;
ListNode*p=head;
ListNode*q=head;
while(q&&q->next)//判断快的就可以了!
{
q=q->next->next;
p=p->next;
if(q==p)return true;
}
return false;
}
};
160. 相交链表
只会用暴力法如下
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*pa=headA;
while(pa)
{
ListNode*pb=headB;
while(pb)
{
if(pb==pa) return pb;
pb=pb->next;
}
pa=pa->next;
}
return pa;
}
};
然后看题解学会了这个双指针法使得两个到达相同的长度再开始判断
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*a=headA,*b=headB;
while(a!=b){
a=(a==NULL)?headB:a->next;
b=(b==NULL)?headA:b->next;
}
return a;
}
};
203. 移除链表元素
point:考虑开头连续删除好几个节点的情况
方法一:标准答案:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode*dummy=new ListNode(0);
dummy->next=head;
ListNode* p=dummy;//加了dummy之后不需要考虑头结点需要删除的特殊情况
while(p&&p->next)
{
if(p->next->val==val)
{
auto tmp=p->next->next;
delete p->next;
p->next=tmp;
}
else p=p->next;
}
return dummy->next;
}
};
方法二:如果要单独考虑头结点的话如下(感谢小刘鸭同学的悉心解答!我明白辽!)
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head&&head->val==val)head=head->next;
ListNode*p=head;
while(p&&p->next){
if(p->next->val==val)p->next=p->next->next;
else p=p->next;
}
return head;
}
};
206. 反转链表
方法一:迭代
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*cur=head,*pre=NULL;
while(cur){
auto tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};
方法二:递归(看了好久才懂但是下一次一定不会写!)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode*p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
};
ps:刘老师的解答
递归到p=head到3以后开始回溯(谢谢刘老师!)
summary
1.对边界条件的考虑:
head==NULL等;
2.对特殊情况的考虑:
对head的删除使得头结点缺失或链表为空—>引用辅助指针:
Node* dummy=new Node(0);
3.加强对递归的学习