92. Reverse Linked List II

来源:互联网 发布:it售后工程师岗位职责 编辑:程序博客网 时间:2024/06/02 07:24

题意易懂,就是烦,要判断m是否是1,2刷想个更好的方法,最好是什么情况都通用的方法。

/** * 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 *p = head;        ListNode *pb = head;        ListNode *q = head;        ListNode *qn = head;        if(m == n) return head;        if(m == 1){            q = q -> next;            for(int i = 3; i <= n; ++ i)                q = q -> next;            qn = q -> next;            ListNode *tp = p;            ListNode *t;            p = p -> next;            while(p != qn){                t = p -> next;                p -> next = tp;                tp = p;                p = t;            }            head -> next = qn;            return q;        }        p = p -> next;        q = q -> next;        for(int i = 3; i <= m; ++ i){            p = p -> next;            pb = pb -> next;        }        for(int i = 3; i <= n; ++ i)            q = q -> next;        qn = q -> next;        ListNode *e = p;        ListNode *b = q;        ListNode *tp = p;        ListNode *t;        p = p -> next;        while(p != qn){            t = p -> next;            p -> next = tp;            tp = p;            p = t;        }        pb -> next = q;        e -> next = qn;        return head;    }};
0 0
原创粉丝点击