Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
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.
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution:
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode list1, listReversedStart, listReversedEnd;
list1=dummy;
for(int i=1; i<m;i++)
{
list1=head;
head=head.next;
}
listReversedEnd=head;
listReversedStart=head;
for(int i=0; i<=(n-m);i++)
{
ListNode temp = head;
head=head.next;
temp.next = listReversedStart;
listReversedStart = temp;
}
list1.next=listReversedStart;
listReversedEnd.next = head;
return dummy.next;
}
}
No comments :
Post a Comment