Reverse Linked List II

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.

复制代码
 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 }
复制代码

 

 

posted on   Atlas-Zzz  阅读(271)  评论(0编辑  收藏  举报

编辑推荐:
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
阅读排行:
· DeepSeek智能编程
· 精选4款基于.NET开源、功能强大的通讯调试工具
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示