链表
链表题注意项:
1.适时用虚拟头结点会更方便dummyhead
2.注意对空指针的讨论,对空指针是无法访问val或者next的
内存分配与内存释放:
//c++
ListNode* dummyHead = new ListNode;
ListNode* dummyHead = new ListNode(1);//初值val为1,next为NULL
ListNode* dummyHead = new ListNode[100];//创建100个(大小为100的数组)
delete dummyhead;//删单个
delete[] dummyhead;//删数组
//C语言一般是malloc和free
题目:
1.反转链表
点击查看代码
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head||!head->next)return head;
ListNode* t=head->next;
head->next=NULL;//易忽略,头结点后继为空
//头插法
while(t){
ListNode* te=t->next;
t->next=head;
head=t;
t=te;
}
return head;
}
};
2.环形链表
判断链表是否有环,若有,返回环的入口
点击查看代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head||!head->next)return NULL;
ListNode *slow=head,*fast=head;//快慢指针
while(fast){
fast=fast->next;
if(!fast)break;
else{
fast=fast->next;
}
slow=slow->next;
if(fast==slow)break;//如果有环,速度相差1的一定会相遇
}
if(!fast)return NULL;//快指针能走到空,肯定无环
//找环的入口:从相遇点与起点同时出发,它俩相遇点即为入口
ListNode *t=head;//起点
while(t!=slow){
t=t->next;
slow=slow->next;
}
return t;
}
};
浙公网安备 33010602011771号