【跟课笔记】
目录
203. 移除链表元素
循环
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* prev=NULL,*cur=head;
while(cur)
{
if(cur->val==val)
{
if(head==cur)
{
head=cur->next;
free(cur);
cur=head;
}
else
{
prev->next=cur->next;
free(cur);
cur=prev->next;
}
}
else
{
prev=cur;
cur=cur->next;
}
}
return head;
}
递归
struct ListNode* removeElements(struct ListNode* head, int val){
if(head==NULL)
return head;
head->next=removeElements(head->next,val);//删除操作
return head->val==val?head->next:head;
}
206. 反转链表
三指针迭代//做链表一定要画图
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)
return head;
struct ListNode*n1=NULL,*n2=head,*n3=head->next;
while(n2)
{
//翻转
n2->next=n1;
//迭代往后走
n1=n2;
n2=n3;
if(n3)
n3=n3->next;
}
return n1;
}
新建链表头插
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur=head,*newhead=NULL;
while(cur)
{
//保存下一个
struct ListNode*next=cur->next;
//头插
cur->next=newhead;
newhead=cur;
//迭代
cur=next;
}
return newhead;
}
876. 链表的中间结点
快慢指针
struct ListNode* middleNode(struct ListNode* head){
struct ListNode*slow,*fast;
slow=fast=head;
while(fast&&fast->next)
{
slow=slow->next;//走一步
fast=fast->next->next;//走两步
}
return slow;
}
剑指 Offer 22. 链表中倒数第k个节点
快慢指针
struct ListNode* getKthFromEnd(struct ListNode* head, int k){
struct ListNode*slow,*fast;
slow=fast=head;
while(k--)
{
if(fast==NULL)return NULL;
fast=fast->next;//fast先走k步
}
while(fast)//两个一起走
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
剑指 Offer 25. 合并两个排序的链表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL)return l2;
if(l2==NULL)return l1;
struct ListNode* head=NULL,*tail=NULL;
if(l1->val<l2->val){head=tail=l1;l1=l1->next;}
else {head=tail=l2;l2=l2->next;}
while(l1&&l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
tail=l1;
l1=l1->next;
}
else
{
tail->next=l2;
tail=l2;
l2=l2->next;
}
}
if(l1)
{
tail->next=l1;
}
if(l2)
{
tail->next=l2;
}
return head;
}
哨兵位头结点,简化边界问题
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL)return l2;
if(l2==NULL)return l1;
struct ListNode* head=NULL,*tail=NULL;
//哨兵位头结点
head=tail=(struct ListNode*)malloc(sizeof(struct ListNode));
while(l1&&l2)
{
if(l1->val<l2->val)
{
tail->next=l1;
tail=l1;
l1=l1->next;
}
else
{
tail->next=l2;
tail=l2;
l2=l2->next;
}
}
if(l1)
{
tail->next=l1;
}
if(l2)
{
tail->next=l2;
}
struct ListNode*list=head->next;
free(head);
return list;
}