Created
October 19, 2017 02:25
-
-
Save kmurudi/7a7c28b1bd904fc55701c2aeef2758fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ListNode bam = reverseList(temp_head, n - m + 1); // Change 1if (prev != null) // Change 2 prev.next = bam; else head = bam; // Change 3while(head!=null && xx++ <= x){ // Change 4