swap-nodes-in-pairs

/**
*
* @author gentleKay
* Given a linked list, swap every two adjacent nodes and return its head.
* For example,
* Given1->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.
*
* 给定一个链表,交换每两个相邻节点并返回其头部。
* 例如,
* 如果1->2->3->4,您应该将列表返回为2->1->4->3。
* 您的算法应该只使用常量空间。不能修改列表中的值,只能更改节点本身。
*/

/**
 * 
 * @author gentleKay
 * Given a linked list, swap every two adjacent nodes and return its head.
 * For example,
 * Given1->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.
 * 
 * 给定一个链表,交换每两个相邻节点并返回其头部。
 * 例如,
 * 如果1->2->3->4,您应该将列表返回为2->1->4->3。
 * 您的算法应该只使用常量空间。不能修改列表中的值,只能更改节点本身。
 */

public class Main32 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ListNode head = new ListNode(1);
		head.next = new ListNode(2);
		head.next.next = new ListNode(3);
		head.next.next.next = new ListNode(4);
		System.out.println(Main32.swapPairs(head));
		
	}
	public static class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
	 		next = null;
		}
	}
	
	public static ListNode swapPairs(ListNode head) {
		//递归出口
        if(head == null || head.next == null)
            return head;
        //每组相邻节点的第二个节点
        ListNode newNode = head.next;
        //每组相邻节点的第一个节点的next指针指向下一组已反转的第一个节点
        head.next = swapPairs(head.next.next);
        //每组相邻节点的第二个节点的next指针指向改组的第一个节点
        newNode.next = head;
        return newNode;
    }
}

  

原文地址:https://www.cnblogs.com/strive-19970713/p/11301650.html