菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
60
0

Reverse Linked List II

原创
05/13 14:22
阅读数 6186

标签:style   blog   class   code   java   ext   

Link:http://oj.leetcode.com/problems/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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

bubuko.com,布布扣
 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 || head.next == null)
15             return head;
16         ListNode result = new ListNode(0);
17         result.next = head;
18         head = result;
19         ListNode pre = head, cur = head, post = head;
20         int index = 1;
21 
22         while (index < m) {
23             pre = pre.next;
24             index++;
25         }
26         cur = pre.next;
27         post = cur.next;
28         //in this moment, index = m.
29         //example, for{1,2,3,4}, and m = 1, n = 4,
30         //pre is the "virtual" list node point to 1, and cur point to 1, post points to 2
31         //during the iteration:
32         //2->1->3->4
33         //3->2->1->4
34         //4->3->2->1
35         while (index < n) {
36             index++;
37             //get the next element of post
38             ListNode temp = post.next;
39             //post.next should point to the next element of pre
40             post.next = pre.next;
41             //pre.next should point to the post now
42             pre.next = post;
43             //cur.next will points to the temp, and finally, cur will point to null
44             cur.next = temp;
45             //move post to temp
46             post = temp;
47         }
48         return head.next;
49     }
50 }
bubuko.com,布布扣

 

 

Reverse Linked List II,布布扣,bubuko.com

Reverse Linked List II

发表评论

0/200
60 点赞
0 评论
收藏
为你推荐 换一批