画解数据结构刷题之循环链表

循环链表

第一题

struct Node* insert(struct Node* head, int insertVal) {
    struct Node*new=malloc(sizeof(struct Node));
    new->next=new;
    new->val=insertVal;
    if(head==NULL)
    {
head=new;
head->next=new;
return head;
    }
    struct Node*tmp=head;
    do
    {
if(tmp->val > tmp->next->val&&(insertVal >= tmp->val || insertVal<=tmp->next->val))
{
    new->next=tmp->next;
    tmp->next=new;
    return head;
}
else if(tmp->next->val >= insertVal && insertVal>=tmp->val)
        {
            new->next=tmp->next;
            tmp->next=new;
            return head;
        }
        else if(tmp->next==head)
        {
            new->next=tmp->next;
            tmp->next=new;
            return head;
        }
tmp=tmp->next;
    }while(tmp!=head);
    return head;

}

循环条件cur!=head(所给的随意结点)
 

环形链表

第一题

struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode*fast,*slow;
    struct ListNode*ptr;
    fast=slow=ptr=head;
    while(fast&&fast->next)
    {
        if(fast&&fast->next)
        {
            fast=fast->next->next;
        }
        if(slow->next)
        {
            slow=slow->next;
        }
        if(fast==slow)//相遇说明一定有环
        {
while(ptr!=slow)
{
    ptr=ptr->next;
    slow=slow->next;
}
return slow;
        }
    }
    return NULL;
    
}

总结:环形链表或是找倒数第k个结点,可以用快慢指针,快的一次2步,慢的一次1步,考虑快慢如果相遇或者快指针到末尾时的情况,考虑快慢指针的步长差等条件 

第二题

 

struct ListNode* reverseList(struct ListNode* head){
    struct ListNode* front = NULL;
    struct ListNode* mid = head;
    while(mid != NULL)
    {
        struct ListNode* end = mid->next;
        mid->next = front;
        front = mid;
        mid = end;
    }
    return front;
}
int pairSum(struct ListNode* head){
    int ans=0;
    int temp;
struct ListNode*slow=head;
struct ListNode*fast=head->next;//视题目而定
while(fast->next)//因为是偶数
{
    fast=fast->next->next;
    slow=slow->next;
}//slow到达中间结点
struct ListNode*last=slow->next;

    struct ListNode*x=head;
    struct ListNode*y=reverseList(last);
    while(y)
    {
        temp=x->val+y->val;
ans=ans>temp?ans:temp;
x=x->next;
y=y->next;
    }
    return ans;
}

思路:运用快慢指针拿到中间结点,将中间之后的结点翻转,顺序遍历

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值