链表两两反转

public class 链表两两反转 {
    public static class ListNode{
        public int data;
        public ListNode next;
    }
    public ListNode swapPairs(ListNode head){
        // 链表头增加虚拟结点 dummy
        ListNode dummy = new ListNode();
        dummy.next = head;
        head = dummy;
        // 循环退出条件,注意链表结点数单双的情况
        while(head.next != null && head.next.next != null){
            // 开始反转
            ListNode a = head.next;
            ListNode b = a.next;
            head.next = b; // 步骤①
            a.next = b.next; // 步骤①
            b.next = a; // 步骤②
            // dummy 指针前移
            head = a;
        }
        return dummy.next;
    }
}

 

public ListNode swapPairs(ListNode head){  // 链表头增加虚拟结点 dummy  ListNode dummy = new ListNode(-1);  dummy.next = head;  head = dummy;  // 循环退出条件,注意链表结点数单双的情况  while(head.next != null && head.next.next != null){    // 开始反转    ListNode a = head.next;    ListNode b = a.next;    head.next = b; // 步骤①    a.next = b.next; // 步骤①    b.next = a; // 步骤②    // dummy 指针前移    head = a;  }  return dummy.next;}
posted @ 2022-05-22 17:09  七色angel  阅读(76)  评论(0编辑  收藏  举报