【数据结构】算法 Swap Nodes in Pairs 两两交换链表中的节点

Swap Nodes in Pairs 两两交换链表中的节点

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

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表

输入:head = [1,2,3,4]
输出:[2,1,4,3]

就是给你一个链表,2个为一组进行反转,最后不够2的就不反转了。属于K-group 反转的特殊情况

虚头法 dummy head+递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode ret = new ListNode(0, head),p=ret,q=p.next;
        while ((p.next=reverseN(q))!=q){
            p =q;
            q =p.next;
        }
        return ret.next;
    }
     public ListNode reverseN(ListNode head){
        ListNode p =head;
        int count  = 1;
        while(count>0&&p!=null){
            p= p.next; count--;
        }
        if(p==null){ return head;}
        return realreverseN(head,2);
   }

    public ListNode realreverseN(ListNode head,int n){
        if(n==1){return  head;}
        ListNode tail = head.next, p = realreverseN(head.next,n-1);
        head.next=tail.next;
        tail.next =head;
        return p;
    }
}
原文地址:https://www.cnblogs.com/dreamtaker/p/14511943.html