Reverse Linked List | & ||
2016-07-03 07:32
232 查看
Reverse Linked List I
Reverse a linked list.Example
For linked list
1->2->3, the reversed linked list is
3->2->1
分析:
典型的3 pointers 问题。
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { if (head == null) return head; ListNode prev = null; ListNode cur = head; ListNode next = null; while (cur != null) { next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }
Reverse Linked List II
Reverse a linked list from position m to n.Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Example
Given
1->2->3->4->5->NULL, m =
2and n =
4, return
1->4->3->2->5->NULL.
分析:
我们需要把list分成三段。首先得到第一段的最后一个node,然后reverse中间部分。最后把三个部分链接起来。
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param ListNode head is the head of the linked list * @oaram m and n * @return: The head of the reversed ListNode */ public ListNode reverseBetween(ListNode head, int m , int n) { if (m == n) return head; ListNode tempHead = new ListNode(1); tempHead.next = head; // reach the end of the first part ListNode partEnd = tempHead; for(int k = 1; k < m; k++) { partEnd = partEnd.next; } // save it later to connect to the last part. ListNode secondPartTail = partEnd.next; // reverse the middle part ListNode prev = null; ListNode current = partEnd.next; ListNode next = null; for (int p = 1; p <= n - m + 1; p++) { next = current.next; current.next = prev; prev = current; current = next; } // connect three parts partEnd.next = prev; secondPartTail.next = current; return tempHead.next; } }
转载请注明出处:cnblogs.com/beiyeqingteng/
相关文章推荐
- [leetcode] 334. Increasing Triplet Subsequence
- R语言为量化而生
- R语言为量化而生
- ICDM 2014 Paper ShellMiner Mining Organizational Phrases in Argumentative Texts in Social Media
- 【C#】VS2015开发环境的安装和配置(一)2016-08-03更新
- 通过几个Hello World感受.NET Core全新的开发体验
- ASP.NET Core 运行原理剖析1:初始化WebApp模版并运行
- 创业能有多艰辛?
- Redis学习笔记(5)-SpringDataRedis的使用
- Redis学习笔记(5)-SpringDataRedis的使用
- Redis学习笔记(5)-SpringDataRedis的使用
- Redis学习笔记(5)-SpringDataRedis的使用
- ECIR 2016 Paper Modelling User Interest for Zero-query Ranking
- ECIR 2016 Paper Beyond Factoid QA: Effective Methods for Non-factoid Answer Sentence Retrieval
- Copy List with Random Pointer
- 登录模块的增强脚本
- 算法系列之常用算法之一----分治算法
- 687E: TOF
- 687D: Dividing Kingdom II
- 能源管理系统功能简单总结