Leetcode 92.反转链表

时间:2023-03-09 22:07:16
Leetcode 92.反转链表

92.反转链表

反转从位置 mn 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4

输出: 1->4->3->2->5->NULL

详解见图:

Leetcode 92.反转链表

Leetcode 92.反转链表

Leetcode 92.反转链表

Leetcode 92.反转链表

Leetcode 92.反转链表

Leetcode 92.反转链表

Leetcode 92.反转链表

 public class Solution {
public class ListNode {
int val;
ListNode next; ListNode(int x) {
val = x;
}
} public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
for (int i = 0; i < m - 1; i++) {
prev = prev.next;
}
ListNode cur = prev.next;
ListNode post = cur.next;
for(int i=0;i<n-m;i++){
cur.next=post.next;
post.next=prev.next;
prev.next=post;
post=cur.next;
}
return dummy.next;
}
}