Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 31d03a4

Browse files
author
applewjg
committedJan 2, 2015
Reverse Linked List II
Change-Id: I89ec151fb0967b458f61643623a5ba5de943d993
1 parent 93a4f4d commit 31d03a4

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 

‎ReverseLinkedListII.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Jan 2, 2015
4+
Problem: Reverse Linked List II
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/reverse-linked-list-ii/
7+
Notes:
8+
Reverse a linked list from position m to n. Do it in-place and in one-pass.
9+
For example:
10+
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
11+
return 1->4->3->2->5->NULL.
12+
Note:
13+
Given m, n satisfy the following condition:
14+
1 <= m <= n <= length of list.
15+
16+
Solution: in-place & one-pass.
17+
*/
18+
19+
/**
20+
* Definition for singly-linked list.
21+
* public class ListNode {
22+
* int val;
23+
* ListNode next;
24+
* ListNode(int x) {
25+
* val = x;
26+
* next = null;
27+
* }
28+
* }
29+
*/
30+
public class Solution {
31+
public ListNode reverseBetween(ListNode head, int m, int n) {
32+
ListNode dummy = new ListNode(-1);
33+
dummy.next = head;
34+
ListNode first = dummy;
35+
for (int i = 0; i < m - 1; ++i) first = first.next;
36+
ListNode cur = first.next;
37+
for (int i = 0; i < n - m; ++i) {
38+
ListNode move = cur.next;
39+
cur.next = move.next;
40+
move.next = first.next;
41+
first.next = move;
42+
}
43+
return dummy.next;
44+
}
45+
}

0 commit comments

Comments
 (0)
Please sign in to comment.