Leetcode24题
思路分析:
1)凡是看见可能要调整头结点的题,创建个虚拟头结点方便做题
2)因为要两两交换,画图可以发现交换后cur其实是后移,next前移
所以需要pre辅助指针来指向需要调整结点的前驱结点
3)交换完后令pre= cur完成前移
细节处理:需要cur和next两个结点来存储需要更改的两个结点。确保在重新连接当前结点后仍然可以访问后续结点
public ListNode swapPairs(ListNode head) {
ListNode ans = new ListNode(-1);
ans.next = head;
if(head == null){
return head;
}
ListNode pre = ans;
while(pre.next != null && pre.next.next != null){
ListNode cur = pre.next;
ListNode next = cur.next;
cur.next = next.next;
next.next = cur;
pre.next = next;
pre=cur;
}
return ans.next;
}