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; }