zoukankan      html  css  js  c++  java
  • [LeetCode24]Swap Nodes in Pairs

    题目:

    Given a linked list, swap every two adjacent nodes and return its head.

    For example,
    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    交换链表相邻结点

    思路:只要保存头结点,然后理清交换结点位置就好了

      例如链表现在是1->2->3->4,head指向1,新建一个结点root,root->next指向head

    第一次循环:pre指向root,要交换12,首先保存2的下一个结点3,接下来让pre->next为2,2的next为1,1的next为刚才保存的3,然后让head指向3,pre指向1就好了,然后继续 

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if( head == NULL || head->next == NULL) return head;
            ListNode *root = new ListNode(0);
            root->next = head;
            ListNode *pre = root;
            while(head && head->next)
            {
                ListNode* tmp = head->next->next;
                pre->next = head->next;
                pre->next->next = head;
                head->next = tmp;
                pre = head;
                head = head->next;
            }
            return root->next;
        }
    };
  • 相关阅读:
    Jenkins动态部署方案
    01-Java学习笔记
    Tcp实现简单的大小写转换功能
    JavaScript 执行环境 与 变量对象
    JQuery
    JavaScript模板引擎
    ECMA6
    谷歌控制台
    prototype 与 __proto__
    JavaScript Math
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5152169.html
Copyright © 2011-2022 走看看