Leetcode 92.反转链表

92.反转链表

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

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

示例:

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

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

 

详解见图:

 

 1 public class Solution {
 2     public class ListNode {
 3         int val;
 4         ListNode next;
 5 
 6         ListNode(int x) {
 7             val = x;
 8         }
 9     }
10 
11     public ListNode reverseBetween(ListNode head, int m, int n) {
12         if (head == null) {
13             return null;
14         }
15         ListNode dummy = new ListNode(0);
16         dummy.next = head;
17         ListNode prev = dummy;
18         for (int i = 0; i < m - 1; i++) {
19             prev = prev.next;
20         }
21         ListNode cur = prev.next;
22         ListNode post = cur.next;
23         for(int i=0;i<n-m;i++){
24             cur.next=post.next;
25             post.next=prev.next;
26             prev.next=post;
27             post=cur.next;
28         }
29         return dummy.next;
30     }
31 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10163072.html