链表-逐对逆序链表

//逐对逆序链表
public class Node{
    public int value;
    public Node next;
    public Node(int data){
        this.value=data;
    }
}
//递归实现
public Node reversePairRecursive(Node head){
    Node tmp;
    if(head==null||head.next==null){
        return;
    }else{
        //逆置第一对
        tmp=head.next;
        head.next=tmp.next;
        head=tmp;
        //链表余下部分继续递归调用该函数
        head.next.next=reversePairRecursive(head.next.next);
        return head;
    }
}

//迭代实现
public Node reversePairIterative(Node head){
    Node tmp1=null;
    Node tmp2=null;
    while(head!=null&&head.next!=null){
        if(tmp1!=null){
            tmp1.next.next=head.next;
        }
        tmp1=head.next;
        head.next=head.next.next;
        tmp1.next=head;
        if(tmp2==null){
            tmp2=tmp1;
        }
        head=head.next;
    }
    return tmp2;
} 

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/88430641