参考上一题翻转:链表中的每k个一组翻转。
public ListNode swapPairs (ListNode head) {
// write code here
if(head==null||head.next==null) return head;//只有一个或者没有
ListNode result = new ListNode(0);
result.next = head;
ListNode pre = result,cur = head,temp;
for(; cur != null && cur.next != null;){
//pre是前置指针,cur是当前位置,temp是零时位
temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
//已经交换成功
pre.next = temp;
//移动pre和cur,便于下一次更新
pre = cur;
cur = cur.next;
}
return result.next;
}
京公网安备 11010502036488号