92. Reverse Linked List | & ||
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 { 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 class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if (m == n) return head; 4 ListNode tempHead = new ListNode(1); 5 tempHead.next = head; 6 7 // reach the end of the first part 8 ListNode firstPartEnd = tempHead; 9 for (int k = 1; k < m; k++) { 10 firstPartEnd = firstPartEnd.next; 11 } 12 // save it later to connect to the last part. 13 ListNode secondPartEnd = firstPartEnd.next; 14 15 // reverse the middle part 16 ListNode prev = null; 17 ListNode curr = firstPartEnd.next; 18 ListNode next = null; 19 20 for (int p = 1; p <= n - m + 1; p++) { 21 next = curr.next; 22 curr.next = prev; 23 prev = curr; 24 curr = next; 25 } 26 // connect three parts 27 firstPartEnd.next = prev; 28 secondPartEnd.next = current; 29 30 return tempHead.next; 31 } 32 }
转载请注明出处:cnblogs.com/beiyeqingteng/