首页 > 代码库 > 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->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 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。