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

Problem Solving Ideas:

Reverses the variant of the entire list, specifying the start and end points. Because m=1 changes the head node, it joins a dummy head node  1. Find the M-1 node in the original list start: The reversed part will be returned to the node after the change. Move from dummy to m-1  D->1->2->3->4->5->NULL       |      St  2. A partial list of links with a length of L = n-m+1 is reversed starting with P = Start->next.             __________            |                  |            |                 vd->1->2<-3<-4    5->null     & nbsp              |     |           |       St    p          h0 &nbs P        3. Last reply              __________            |                  |    &NBSP       |                 vd->1   2<-3<-4    5->null   &NBSP ;                |________|                

Java code:20160601
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Reversebetween (ListNode head,intMintN) {//iterative//Base Case        if(Head = =NULL|| Head.next = =NULL|| M < 1 | | M >=N) {returnHead; } ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode Pre=dummy; ListNode cur=Head; //move m-1 to the node before reverse start        intCount = 1;  while(Count <m) {Pre=cur; Cur=Cur.next; Count++; } ListNode beforereverse=Pre; ListNode Startreverse=cur;  while(Count <=N) {ListNode next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; Count++; } Beforereverse.next=Pre; Startreverse.next=cur; returnDummy.next; }}

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-reverse-linked-list-ii.html

Leetcode 92. Reverse Linked List II

Related Article

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.