首页 > 代码库 > LeetCode Reverse Linked List II

LeetCode Reverse Linked List II

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode reverseBetween(ListNode head, int m, int n) {14             if (head==null) {15                 return null;16             }17             if(n==m){18                 return head;19             }20             ListNode temp=head,doRe = null,second=null,first=null,last=null;21             int i=1;22             23             while (temp!=null) {24                 if (i==m-1) {25                     first=temp;26                 }27                 if (i==m) {28                     doRe=temp;29                 }30                 if (i==n) {31                     last=temp;32                     second=temp.next;33                     if(first!=null) first.next=last;34                     last.next=null;35                     36                     break;37                 }38                 ++i;39                 temp=temp.next;40             }41             reverse(doRe);42             doRe.next=second;43             if (m>1) {44                 return head;45             }else {46                 return last;47             }48             49     }50     private void reverse(ListNode head) {51         ListNode pre = null,curr,next;52 53         curr=head;54         if (head==null) {55             return;56         }57         while (curr!=null) {58             next=curr.next;59             curr.next=pre;60             pre=curr;61             curr=next;62         }63     }64 }

 

LeetCode Reverse Linked List II