翻转链表二

Reverse a linked list from position m to n.

 Notice

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

Example

Given 1->2->3->4->5->NULL, m = 2 and n = 4, return1->4->3->2->5->NULL.

要注意是否从第一个节点开始翻转,1)是则保存第n+1个节点,进行翻转,然后返回s2)否则保存第m-1个节点,和第n+1个节点,翻转

/**
 * Definition of singly-linked-list:
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The head of linked list.
     * @param m: The start position need to reverse.
     * @param n: The end position need to reverse.
     * @return: The new head of partial reversed linked list.
     */
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // write your code here
        int i = m;
        int j = n - m;
        ListNode *p = head;
        int count = 0;
        while(p != NULL)
        {
            p = p->next;
            count++;
        }
        if(count < n)return NULL;
        p = head;
        while(i > 2)
        {
            p = p->next;
            i--;
        }
        ListNode *bf = p;
        if(m != 1)p = p->next;
        ListNode *q = p;
        while(j >= 0)
        {
            q = q->next;
            j--;
        }
        ListNode *s = q;
        while(p != q)
        {
            ListNode *tmp = p->next;
            p->next = s;
            s = p;
            p = tmp;
        }
        if(m != 1)
        {
            bf->next = s;
            return head;
        }
        else return s;
        
    }
};

 

转载于:https://www.cnblogs.com/dynas/p/7003801.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值