题目:
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
思路:
linkedlist的题有点混乱 需要指针
这道题是有三个 start node1 和node2
先遍历,把start放在node1前面。
然后start.next是node1
node1的next是node2
然后开始交换。一个一个连接。
3-2
3-2-4
1-3-2-4.
然后把node2给4。
想不明白可以看开头,这三个必须有
node1.next
node2.next
startpoint.next
Code:
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
if(head==null||head.next==null)
return dummy.next;
ListNode startpoint = dummy;
ListNode node1=null;
ListNode node2=null;
for(int i = 0;i<n;i++){
if(i<m-1){
startpoint= startpoint.next;
}else if(i==m-1){
node1 = startpoint.next;
node2 = node1.next;
}else{
node1.next = node2.next; //2-4
node2.next = startpoint.next;//3-2-4
startpoint.next = node2; // 1-3-2-4
node2 = node1.next;
}
}
return dummy.next;
}