Reverse Linked List Ii--leetcode

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 ≤ mn ≤length of list.

The main idea is to give a single linked list, given a starting point and an end point, reversing the list between the starting point and the end point, requiring: in-situ inversion, one-time traversal.

Solution idea: Because already limited 1 ≤ mn ≤length of list, the set head node points to the first element, the working pointer goes first m step, uses the head interpolation method to reconstruct the data between M and N, Finally, the next pointer on the m position points to the position of the original n+1.

This time the code is a bit tangled, Java operations are not as good as C + + proficiency.

 PublicListNode Reversebetween (ListNode head,intMintN) {if(Head = =NULL|| m = =N) {returnHead; }        intCount = N-m; ListNode P=NewListNode (0);        ListNode q; ListNode HEADP=NewListNode (0); ListNode Res=HEADP; P.next=Head; Headp.next=Head;  while(--m > 0) {HEADP=Headp.next; } P=Headp.next; Q=P.next; ListNode Last=p; Headp.next=NULL;  while(count-->= 0) {P.next=Headp.next; Headp.next=p; if(Q! =NULL) {p=Q; Q=Q.next; } Else{p=NULL; }} Last.next=p; /*while (res!=null) {System.out.println (res.val);        Res=res.next; }*/        returnRes.next; }

Reverse Linked List Ii--leetcode

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.