Leetcode 92. Reverse Linked List II

Source: Internet
Author: User

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 the list.

Idea: According to test instructions, you need to reverse the node between a given number
Specifically, add a pseudo-head node to the original list (the benefits of this: the original node of the list can be treated as a normal node, convenient to operate), and get the beginning and end nodes of the reverse node (for ease of operation, the first node that starts the reversal node and the last node of the final reversal node, That is, the middle part is the node that needs to be reversed, and then reverses the middle node to get the final sequence.

The specific implementation is as follows:

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {val = x;} *} * / Public  class solution {     PublicListNodeReversebetween(ListNode Head,intMintN) {if(Head = =NULL){return NULL; }if(M = = N) {returnHead }intFlag =0; ListNode P1 = head;//used to point to the previous node that started the reverse nodeListNode P2 = head;///used to point to the last node of the reverse node P1---the node between P2 is the node to invert (not including P1 p2)ListNode Phead =NewListNode (0);        Phead.next = head; ListNode p = phead; while(P! =NULL) {flag++;if(flag = = m) {p1 = p;//point to the previous node of the start Reversal node}if(Flag = = n+1) {P2 = P.next;//point to the last node of the end reversal node                 Break;        } p = P.next;        } ListNode pp1 = P1.next;        ListNode pp2 = Pp1.next;        ListNode pp3 = Pp2.next; Pp1.next = p2; while(pp3! = p2)            {pp2.next = PP1;            PP1 = PP2;            PP2 = PP3;        PP3 = Pp3.next;        } pp2.next = PP1; P1.next = PP2;returnPhead.next; }}

Leetcode 92. Reverse Linked List II

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.