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;
        }
    };
  • 相关阅读:
    测试方案
    测试需求
    软件测试知识点总结
    自动化测试
    测试——缺陷报告包括那些内容,由什么组成
    测试——缺陷的类型
    软件测试工具简介
    测试工程师
    剑指offer系列21--二叉搜索树的后续遍历序列
    剑指offer系列20--从上到下打印二叉树
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5152169.html
Copyright © 2011-2022 走看看