zoukankan      html  css  js  c++  java
  • 24.Swap Nodes in Pairs

    给定一个链表,从头开始,将其相邻的2个节点翻转。
    Given 1->2->3->4, you should return the list as 2->1->4->3.


    思路:
    用一个临时节点tmp_head,先指向当前头结点head的下一个节点,然后移动临时节点,再指向当前头结点,再移动头节点。需要注意的点有两个: 1. 需要先保存头节点下一次更新,因为 head->next 指向 他的下一个next,然而让其反向指回 head了,就断了之前 head->next->next 这个节点的联系了。 2.死循环,因为head指向head->next,而head->next指向head->next->next,现在将head->next指向head,而head还是保持指向head->next的,所以这儿就闭环了。

    ListNode* swapPairs(ListNode* head) {
        if (!head) return NULL;
        ListNode* res = new ListNode(-1), * tmp_head = res, * next_head_update = res;
        if (head->next == NULL) return head;
        while (head && head->next) {
            tmp_head->next = head->next;
            tmp_head = tmp_head->next;
            next_head_update = head->next->next; //保存下一次head更新节点
            tmp_head->next = head;
            tmp_head = tmp_head->next;
            tmp_head->next = next_head_update; //打破闭环
            head = next_head_update; //更新head节点
        }
        return res->next;
    }

    Java 版:

    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode res = new ListNode(-1), tmpHead = head, tmp = res;
            while(head != null){
                if(head.next == null) break; // 奇数个数节点,最后一个直接不管
                tmpHead = head.next.next;
                tmp.next = head.next;
                tmp = tmp.next;
                tmp.next = head;
                tmp = tmp.next;
                tmp.next = null; // 防止构成一个圈,破坏闭环
                head = tmpHead;
            }
            tmp.next = head; // 不管最终是奇数、偶数,这儿都能适用兜底
            return res.next;
        }
    }
  • 相关阅读:
    Cache 在选择的几点思考
    英语12种记忆单词的方法
    对啊英语音标---二、ghywr这些辅音怎么发音
    日常英语---八、REBOOT
    日常英语---一、纸质版还是电子版
    日常英语---四、vis.js是什么
    日常英语---二、注册google的api的key
    日常英语---七、[Updated November 14 at 4:10 PM PST] Scheduled Game Update
    日常英语---六、Maplestory Illium
    日常英语---三、网页查找单词用什么
  • 原文地址:https://www.cnblogs.com/luo-c/p/12918667.html
Copyright © 2011-2022 走看看