Given a linked list, swap every two adjacent nodes and return its head.题目要求输入一个链表,咱们将相邻的两个节点的顺序翻转。最后返回头节点。同时题目要求只能占用常数空间,而且不能改变节点的值,改变的是节点自己的位置。node
例如,
输入 1->2->3->4, 你应该返回的链表:2->1->4->3.spa
public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while(current.next != null && current.next.next != null){ ListNode first = current.next; ListNode second = current.next.next; first.next = second.next; second.next = first; current.next = second; current = current.next.next; } return dummy.next; }