LeetCode Reverse Linked List II
2015-07-01 22:26
369 查看
Description:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
return
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution:
只需要按照题目给出的模拟一下,链表的基本操作。注意+1 -1的区间操作。
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->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution:
只需要按照题目给出的模拟一下,链表的基本操作。注意+1 -1的区间操作。
import java.util.*; public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (m == n) return head; ListNode pre_node_m, next_node_n; ListNode neoHead, neoTail, current, next; if (m == 1) { next_node_n = getNode(head, n + 1); neoTail = neoHead = null; current = head; for (int i = m; i <= n; i++) { next = current.next; if (neoHead == null) { neoHead = neoTail = current; current.next = null; } else { current.next = neoHead; neoHead = current; } current = next; } head = neoHead; neoTail.next = next_node_n; } else { pre_node_m = getNode(head, m - 1); next_node_n = getNode(head, n + 1); current = pre_node_m.next; neoTail = neoHead = null; for (int i = m; i <= n; i++) { next = current.next; if (neoHead == null) { neoHead = neoTail = current; current.next = null; } else { current.next = neoHead; neoHead = current; } current = next; } pre_node_m.next = neoHead; neoTail.next = next_node_n; } return head; } ListNode getNode(ListNode head, int n) { ListNode temp = head; n--; while (n > 0) { temp = temp.next; n--; } return temp; } }
相关文章推荐
- 2015070103 - EffactiveJava笔记 - 第47条 了解和使用类库(2)
- MVP, MVC, MVVM, 傻傻分不清楚~
- ubuntu下安装pycharm的方法
- MM Reference material
- Add Binary
- 经验解决Fragment 被 Replace后仍旧可见的问题
- 摘录-IT企业必读的200个.NET面试题-04 字符串、集合和流的使用
- netstat TIME_WAIT
- lombok的使用和原理
- 排序算法之归并排序Java版
- Gensim官方介绍翻译
- fcitx
- 2015年换工作感想
- 黑马day11 c3p0数据库连接池
- 第2章 数字之魅——求二进制中1的个数
- 连接mysql报错:error 2003 (hy000):can't connect to mysql server on 'localhost' (10061)
- 毕业啦,上班第一天
- Android实例之有道词典
- LintCode 寻找缺失的数
- 腾讯实习经验