zoukankan      html  css  js  c++  java
  • [数据结构与算法]给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

    给定 1->2->3->4, 你应该返回 2->1->4->3.

    这个题目一看很简单,就是让后驱节点指向前驱节点,然后前驱节点指向后驱节点的后驱节点,但是后驱的节点也需要交换,所以有点棘手。
    思路就是列举如下图
    1 -> 2 -> X -> Y
    | | |
    left right aft
    第一步: 初始化 preNode = right ,left,right , aft四个节点  指向
    第二步: right.next = left, pre.next = right, pre = left;

    1 <-> 2 X -> Y
             |           |    | 
           pre.next     left   right  aft
    如果X = null, pre.next = null, 
    如果X != null, Y = null, pre.next = X;
    否则 Y -> X (Y.next = X), pre.next = Y, pre = X;
    上代码
    public ListNode swapPairs(ListNode head) {
    //边界条件 如果没有/只有一个节点,直接返回
            if(head == null || head.next == null)
                return head;
            
            ListNode left = head, right = head.next, aft = right.next;
            ListNode preHead = new ListNode(-1);
            preHead.next = right;
            ListNode pre = new ListNode(-1);//前驱节点
            while(right != null){
                
                right.next = left;
                pre.next = right;
                pre = left;
                
                if(aft == null){
                    pre.next = null;
                    break;
                }
                left = aft;
                right = aft.next;
                
                if(right == null)
                {
                    pre.next = left;
                }else{
                    aft = right.next;
                }
            }
            return preHead.next;
        }
    

      思路就是

    欢迎关注Java流水账公众号
  • 相关阅读:
    [LeetCode#252] Meeting Rooms
    [LeetCode#247] Strobogrammatic Number II
    [LeetCode#265] Paint House II
    [LeetCode#256] Paint House
    [LeetCode#279] Perfect Squares
    [LeetCode#259] 3Sum Smaller
    [LeetCode#261] Graph Valid Tree
    [LeetCode#271] Encode and Decode Strings
    xfsdump的选项-L和-M
    Centos7 报错welcome to emergency mode
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/11462560.html
Copyright © 2011-2022 走看看