前言
1.移除链表元素
1.双指针尾插
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(!head)
{
return NULL;
}
struct ListNode*fast=head->next;
struct ListNode*slow=head;
while(fast)
{
if(fast->val==val)
{
struct ListNode*next=fast->next;
slow->next=fast->next;
free(fast);
fast=next;
}
else
{
slow=slow->next;
fast=fast->next;
}
}
if(head->val==val)
{
struct ListNode*next=head->next;
free(head);
head=next;
}
return head;
}
2.尾插解决
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* tail=head;
struct ListNode*cur=NULL;
struct ListNode*newhead=NULL;
if(head==NULL)
{
return NULL;
}
while(tail)
{
if(tail->val!=val)
{
if(cur==NULL)
{
cur=newhead=tail;
}
else
{
cur->next=tail;
cur=cur->next;
}
tail=tail->next;
}
else
{
struct ListNode*next=tail->next;
free(tail);
tail=next;
}
if(cur)
{
cur->next=NULL;
}
}
return newhead;
}
3.带头节点
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* tail=head;
struct ListNode*cur,*guard;
cur=guard=(struct ListNode*)malloc(sizeof(struct ListNode));
if(head==NULL)
{
return NULL;
}
while(tail)
{
if(tail->val!=val)
{
cur->next=tail;
cur=cur->next;
tail=tail->next;
}
else
{
struct ListNode*next=tail->next;
free(tail);
tail=next;
}
}
cur->next=NULL;
struct ListNode*newhead=guard->next;
free(guard);
return newhead;
}
2.合并两个有序数组
1.双指针
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
if(list1==NULL)
{
return list2;
}
if(list2==NULL)
{
return list1;
}
struct ListNode*head,*tail;
head=tail=NULL;
while(list1&&list2)
{
if(list1->val>list2->val)
{
if(head==NULL)
{
head=tail=list2;
}
else
{
tail->next=list2;
tail=tail->next;
}
list2=list2->next;
}
else
{
if(head==NULL)
{
head=tail=list1;
}
else
{
tail->next=list1;
tail=tail->next;
}
list1=list1->next;
}
}
if(list1)
tail->next=list1;
if(list2)
tail->next=list2;
return head;
}
2.带头结点
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode*tail,*guard;
tail=guard=(struct ListNode*)malloc(sizeof(struct ListNode));
guard->next=NULL;
while(list1&&list2)
{
if(list1->val>list2->val)
{
tail->next=list2;
tail=tail->next;
list2=list2->next;
}
else
{
tail->next=list1;
tail=tail->next;
list1=list1->next;
}
}
if(list1)
tail->next=list1;
if(list2)
{
tail->next=list2;
}
struct ListNode*head=guard->next;
free(guard);
return head;
}
3.链表的中间节点
struct ListNode* middleNode(struct ListNode* head)
{
if(head==NULL)
{
return NULL;
}
struct ListNode*fast=head;
struct ListNode*slow=head;
while (fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
4.链表中倒数第k个结点
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k )
{
struct ListNode* slow = pListHead;
struct ListNode* fast = pListHead;
while(k--)
{
if(fast == NULL)
return NULL;
fast = fast->next;
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}