Reverse Linked List II

本文介绍了一种在给定范围内反转链表的有效方法,并通过示例详细解释了该算法的工作原理及实现步骤。讨论了特殊情况的处理方式,包括空链表、单节点链表以及指定范围等于整个链表长度的情况。

Reverse Linked List II      

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

思路:1, 先判断head是否为空或单节点或m==n,这三种情况都直接返回head即可。

             2,需要把m-n之间反转。

                               2.1,  m==1 反转头节点就是head,反转前n-m 个。

                                2.2, m!=1 先找到反转头节点的前一个节点,把他和反转头节点断开,反转后再连起来

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
//反转链表,但是只反转m-n 之间的
     ListNode* inverse(ListNode* head,int k)
    {
         if(head==NULL||head->next==NULL) return head;;
        ListNode*p=head,*q=head->next;
        int count=0; 
//count计数,反转m-n次就不反转了,一定要循环体内其他语句执行完再count加1
        while(q&&count<k)
        {
            
            p->next=q->next;
            q->next=head;
            head=q;
            q=p->next;
            count++;
        }
        return head;
    } 
//这里有很多特殊条件要考虑:1,head或head->next为null;2, m==n,就不用操作了;3, m==1,就不用找反转的头节点了
    ListNode *reverseBetween(ListNode *head, int m, int n) {
       if(head==NULL||head->next==NULL) return head;
       if(m==n)return head;
       int k=n-m;
       if(m==1) 
       {
           head= inverse(head,k);
           return head;
       }
//m!=1时,先找到需要反转的头节点的前一个,把他和需要反转的头节点断开,反转后再连上,所以counter==m-1时就取出来
       int counter=0;
       ListNode*p=head,*tm;
       while(p&&counter<m)
       {
           counter++;          
        if(counter==(m-1))tm=p;
         //  if(counter==n)tn=p;
        // counter++;
           p=p->next; //这里注意先取出p,在令p=p->next;
       }
      ListNode*h=tm->next;
      tm->next==NULL;
      h=inverse(h,k);
      tm->next=h;
      return head;      
    }
};





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值