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
题意:
给定一个链表,反转第m~n个节点。
反转链表的一般思路
Solution1:
1.用指针找到m和n位置
2.反转m和n之间的链表
code
1 class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if(head==null) return head; 4 5 ListNode dummy = new ListNode(-1); 6 7 dummy.next = head; 8 9 ListNode mNode = head; 10 ListNode preM = dummy; 11 ListNode nNode = head; 12 13 for (int i = 1; i < m ; i++) { 14 preM = mNode; 15 mNode = mNode.next; 16 } 17 18 for (int i = 1; i <n ; i++) { 19 nNode = nNode.next; 20 } 21 22 while(mNode != nNode){ 23 preM.next = mNode.next; 24 mNode.next = nNode.next; 25 nNode.next = mNode; 26 mNode = preM.next; 27 } 28 return dummy.next; 29 } 30 }