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;
        }
    };
  • 相关阅读:
    php环境下所有的配置文件以及作用
    获取登陆用户的ip
    curl模拟post和get请求
    linux 下安装php curl扩展
    php常用面试知识点
    git使用步骤
    laravel框架基础知识点
    ci框架基础知识点
    ajax
    Mysql 中需不需要commit
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5152169.html
Copyright © 2011-2022 走看看