Skip to content

Instantly share code, notes, and snippets.

@kmurudi
Created October 19, 2017 02:25
Show Gist options
  • Select an option

  • Save kmurudi/7a7c28b1bd904fc55701c2aeef2758fc to your computer and use it in GitHub Desktop.

Select an option

Save kmurudi/7a7c28b1bd904fc55701c2aeef2758fc to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || head.next==null) return head;
if(m==n) return head;
int first_count = 1;
int second_count = 1;
ListNode temp_head = head;
ListNode prev = null;
ListNode next_head = head;
while(first_count++!=m){
prev = temp_head;
temp_head = temp_head.next;
}
while(second_count++!=n){
//prev = temp_head;
next_head = next_head.next;
}
ListNode bam = reverseList(temp_head,n);
ListNode end_bam = bam;
while(end_bam.next!=null){
end_bam = end_bam.next;
}
prev.next = bam;
end_bam.next = next_head.next;
return head;
}
public ListNode reverseList(ListNode head, int x) {
int xx=1;
ListNode n = null;
while(head!=null && xx++!=x){
ListNode new1 = new ListNode(head.val);
new1.next = n;
n = new1;
head = head.next;
}
return n;
}
}
@nmvk
Copy link
Copy Markdown

nmvk commented Oct 19, 2017

ListNode bam = reverseList(temp_head, n - m + 1); // Change 1
if (prev != null) // Change 2 prev.next = bam; else head = bam; // Change 3

while(head!=null && xx++ <= x){ // Change 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment