92. 反转链表 IIC语言

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
通过次数115,960提交次数219,660

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一种思路
重新申请链表空间
在给定区间使用头插法
在非给定区间使用尾插法
第二种思路
直接将给定区间使用头插法重新写一份链表a
然后将a直接插进原链表

第二种思路代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseBetween(struct ListNode* head, int left, int right){
    //结合头插法,但最后一个的指针得留着
    if(left==right) return head;
    int count =1;
    struct ListNode * last = head;
    struct ListNode * cur = head;
    struct ListNode * temp = (struct ListNode*)malloc(sizeof(struct ListNode));
    temp->val =0;
    temp->next= NULL;
    struct ListNode * temp1 = NULL;
    while(cur!=NULL)
    {
        if(count >=left&&count<=right)
        {
         
          struct ListNode * dd = (struct ListNode*)malloc(sizeof(struct ListNode));
          dd->val = cur->val;
          dd->next=temp->next;
          temp->next = dd;
           if(count==left) 
             {
                temp1=dd;
            
             }
           cur=cur->next;
           if(count==right)
           {   
               temp1->next=cur;
               break;


           }
           count++;
        }
       else{
        last=cur;
        cur=cur->next;
        count++;
       }
          
        
    }
    if(left==1)
    {
        head=temp->next;
        //temp1->next=cur;
    }
    else
    {
        last->next = temp->next;
      // temp1->next = cur;
       // printf("%d",temp1->val);
       // printf("%d",cur->val);
    }
    
    while(temp)
    {
       // printf("%d",temp->val);
        temp=temp->next;
    }
    return head;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值