码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List | & ||

时间:2016-07-03 08:12:53      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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 问题。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param head: The head of linked list.
15      * @return: The new head of reversed linked list.
16      */
17     public ListNode reverse(ListNode head) {
18         if (head == null) return head;
19         ListNode prev = null;
20         ListNode cur = head;
21         ListNode next = null;
22         while (cur != null) {
23             next = cur.next;
24             cur.next = prev;
25             prev = cur;
26             cur = next;
27         }
28         return prev;
29     }
30 }

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 = 2 and n = 4, return 1->4->3->2->5->NULL.

分析:

我们需要把list分成三段。首先得到第一段的最后一个node,然后reverse中间部分。最后把三个部分链接起来。

 1 /**
 2  * Definition for ListNode
 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     /**
14      * @param ListNode head is the head of the linked list 
15      * @oaram m and n
16      * @return: The head of the reversed ListNode
17      */
18     public ListNode reverseBetween(ListNode head, int m , int n) {
19         if (m == n) return head;
20         ListNode tempHead = new ListNode(1);
21         tempHead.next = head;
22 
23         // reach the end of the first part
24         ListNode partEnd = tempHead;
25         for(int k = 1; k < m; k++) {
26             partEnd = partEnd.next;
27         }
28         // save it later to connect to the last part.
29         ListNode secondPartTail = partEnd.next; 
30         
31         // reverse the middle part
32         ListNode prev = null;
33         ListNode current = partEnd.next;
34         ListNode next = null;
35         
36         for (int p = 1; p <= n - m + 1; p++) {
37             next = current.next;
38             current.next = prev;
39             prev = current;
40             current = next;
41         }
42         // connect three parts
43         partEnd.next = prev;
44         secondPartTail.next = current;
45         
46         return tempHead.next;
47     }
48 }

转载请注明出处:cnblogs.com/beiyeqingteng/

 

Reverse Linked List | & ||

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5636524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!