- 关键字:反转部分链表
- 难度:Medium
- 题目大意:反转部分链表,要求遍历一次链表完成
题目:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
解题思路:
先建立一个dummy结点,pre结点、cur结点,首先移动cur到需要反转的第一个节点,相应的pre移动到cur前一个结点,用start记录开始反转结点的前一个结点,end记录反转的第一个结点,这么说有点绕,举个例子:
1 -> 2 -> 3 -> 4 ->5 ->NULL , m=2, n=4
反转步骤:
- 建立dummy结点:
dummy -> 1 -> 2 -> 3 -> 4 ->5 -> NULL pre=dummy, start=dummy, cur=head; - 移动cur到要反转的节点:此时,pre=1, start=1, cur=2, end=2;
- 第一次反转:dummy -> 1 <- 2 -> 3 -> 4 ->5 -> NULL, start=1, pre=2, cur=3, end=2;
- 第二次反转:dummy -> 1 <- 2 <- 3 -> 4 ->5 -> NULL, start=1, pre=3, cur=4, end=2;
- 第三次反转:dummy -> 1 <- 2 <- 3 <- 4 ->5 -> NULL, start=1, pre=4, cur=5; end=2;
- 改变start 和end 的next结点:start.next = pre, end.next=cur, dummy -> 1->4->3->2->5->NULL
AC代码:
/**
* 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) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode start = dummy;
ListNode cur = head;
for(int i=0;i<m-1;i++) {
pre = cur;
start = pre;
cur = cur.next;
}
ListNode end = cur;
for(int i=0;i<=n-m;i++) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
start.next = pre;
end.next = cur;
return dummy.next;
}
}
网友评论