LeetCode 92 反轉連結串列 II
阿新 • • 發佈:2019-01-10
反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。
說明:
1 ≤ m ≤ n ≤ 連結串列長度。
示例:
輸入: 1->2->3->4->5->NULL, m = 2, n = 4 輸出: 1->4->3->2->5->NULL
5ms
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(m==n){ return head; } m = m-1; n = n-1; List<ListNode> list = new ArrayList(); ListNode cur = head; while(cur!=null){ ListNode tmp = cur.next; cur.next = null; list.add(cur); cur = tmp; } ListNode a; ListNode b; while(m<n){ a = list.get(m); b = list.get(n); list.set(m,b); list.set(n,a); m++; n--; } ListNode newHead = list.get(0); ListNode next; for(int i=0;i<list.size()-1;i++){ next = list.get(i); next.next = list.get(i+1); } return newHead; } }
優化4ms
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n){ ListNode newHead = new ListNode(0); newHead.next = head; ListNode cur = newHead; for(int i=0;i<m-1;i++){ cur = cur.next; } ListNode first = cur; ListNode last = cur.next; ListNode pre = null; cur = cur.next; ListNode tmp; for(int i=0;i<n-m+1;i++){ tmp = cur.next; cur.next = pre; pre = cur; cur = tmp; } first.next = pre; last.next = cur; return newHead.next; } }
優化3ms
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy; for (int i = 0; i < m - 1; i++) { prev = prev.next; } ListNode start = prev.next; ListNode then = start.next; for (int i = 0; i < n - m; i++) { start.next = then.next; then.next = prev.next; prev.next = then; then = start.next; } return dummy.next; } }
給定一個值3,需要對陣列[1,2,3,4,5] 反轉, 需要得到結果 [3,2,1,5,4]
public ListNode reversetTwo(ListNode head,int m,int total){
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode start = pre.next;
ListNode then = start.next;
for(int i=0;i<m-1;i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
int n = total-m;
pre = start;
start = start.next;
then = then.next;
for(int i=0;i<n-1;i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}