24_两两交换链表中的节点

24_两两交换链表中的节点

 

package 链表;

/**
 * https://leetcode-cn.com/problems/swap-nodes-in-pairs/
 * 
 * @author Huangyujun
 *
 */
public class _24_两两交换链表中的节点 {
//    public ListNode swapPairs(ListNode head) {
//        if (head == null)
//            return null;
//        // 头节点妙处多多
    //错误原因:我把虚拟结点的连线写在外头,(其原本需要写在循环里的)
//        ListNode newNode = new ListNode(0);
//        newNode.next = head.next;
//        while (head != null && head.next != null) {
//            ListNode next = head.next;
//            head.next = next.next;
//
//            next.next = head;
//
//            head = head.next;
//        }
//        return newNode.next;
//    }
    //正解:
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode temp = dummyHead;
            while (temp.next != null && temp.next.next != null) {
                ListNode node1 = temp.next;
                ListNode node2 = temp.next.next;
                temp.next = node2;
                node1.next = node2.next;
                node2.next = node1;
                temp = node1;
            }
            return dummyHead.next;
        }
    }
    
    //递归也是要建立在理解函数的基础上哈(本题意是两两交换:
    // 原来: 1,2, 3,4, 5,6 ,递归回来的部分是从 3 开始的 3—6 
    //只需要把前面的两个 1、 2 、和递归回来的3-6,进行连接一下)
    class Solution2 {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode newHead = head.next;
            head.next = swapPairs(newHead.next);
            newHead.next = head;
            return newHead;
        }
    }

}

 

posted @ 2021-12-19 22:36  一乐乐  阅读(30)  评论(0编辑  收藏  举报