Leetcode -- Reverse Linked List II select some nodes in the Linked List in Reverse order (AC)

Source: Internet
Author: User

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 m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

It is still complicated to deal with this problem. Many boundary test cases need to be considered. My general idea is to mark the previous node of m and the node behind n cyclically, and use the node behind n as the pre of the current reverse node first, then, complete the reverse order of the selected node parts n-m times, and point the previous node of the marked m node to the header node of the backward part. Consider special cases. The code is as follows:

class Solution {public:    ListNode *reverseBetween(ListNode *head, int m, int n) {        if(head==NULL || m<0 || n<0)            return head;        if(head->next == NULL || m==n)            return head;        ListNode *head2=NULL,*pre,*cur,*temp=head;        for(int i=0; i
 
  next;        }        for(int i=m;i
  
   next;            cur->next = pre;            pre = cur;            cur = temp;        }        if(m==1)            return pre;        head2->next = pre;        return head;    }};
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.