CODE 108: Swap Nodes in Pairs

来源:互联网 发布:php json encode 在线 编辑:程序博客网 时间:2024/05/21 14:50

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

public ListNode swapPairs(ListNode head) {// Start typing your Java solution below// DO NOT write main() functionListNode newHead = new ListNode(0);ListNode tmpHead = newHead;ListNode tmp = head;while (null != tmp && null != tmp.next) {ListNode first = tmp;ListNode second = tmp.next;tmp = second.next;tmpHead.next = second;tmpHead.next.next = first;tmpHead = tmpHead.next.next;}if (null != tmp) {tmpHead.next = tmp;tmpHead = tmpHead.next;}tmpHead.next = null;return newHead.next;}