zoukankan      html  css  js  c++  java
  • [LeetCode] 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交换,5,6交换。这里注意一下起点,同时交换时候注意顺序即可。

    /**
     * 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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(head == NULL || head -> next == NULL)
                return head;
                
            ListNode *root = NULL, *last = NULL, *first = head, *second = NULL, *tmp = NULL;
            while(first != NULL)
            {
                if(first -> next == NULL) break;
                second = first -> next;
                if(last == NULL)
                {
                    root = second;
                    tmp = second -> next;
                    second -> next = first;
                    first -> next = tmp;
                    last = first;
                    first = tmp;
                    continue;
                }
                
                tmp = second -> next;
                last -> next = second;
                second -> next = first;
                first -> next = tmp;
                last = first;
                first = tmp;
            }
            return root;
        }
    };
  • 相关阅读:
    vue实战使用ajax请求后台数据(小白)
    jQuery实现tab栏切换效果
    jQuery下的ajax实例
    数据库之视图更新
    SQL Server 全文索引创建
    SQL Server 分区表
    数据快照 (Database Snapshot)
    FileStream
    ODBC,OLEDB,ADO,ADO.net,JDBC 理解
    拖延症?贪玩?来试试"百万金币时间管理法"
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3417165.html
Copyright © 2011-2022 走看看