当前位置:编程学习 > C/C++ >>

[leetcode]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 ? m ? n ? length of list.

  

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(m == n) return head;
        
       ListNode *p = NULL, *q = head;
       
       for(int i = 0; i < m-1; i++){
           p = q;
           q = q -> next;
       }
       
       ListNode *e1 = p, *s1 = q;
       
       p = q;
       q = q->next;
       
       ListNode *r;
       for(int i = m; i < n; i++){
           r = q->next;
           q->next = p; 
           p = q;
           q = r;
       }
       
       if(s1) s1->next = q;
       
       if(e1) e1->next = p;
       else head = p;
       
       return head;
        
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,