LeetCode---reverse-linked-list-ii(一段区间内的链表逆序)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/90757835

题目描述

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

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

return1->4->3->2->5->NULL.

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

                                   

                                           

                                          

上面就完成了s->r->q的转变,以此类推

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        ListNode L = ListNode(0);
        L.next = head;
        ListNode *p = &L;
        ListNode *q = head;
        for(int i=1;i<m;i++)
        {
            p = q;
            q = q->next;
        }
        for(int i=0;i<n-m;i++)
        {
            ListNode *t = q->next;
            q->next = t->next;
            t->next = p->next;
            p->next = t;
        }
        return L.next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/90757835
今日推荐