zoukankan      html  css  js  c++  java
  • Swap Nodes in Pairs -- leetcode

    题目描述:
    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) {
            if (head == NULL || head->next == NULL) return head;
            ListNode *newList = new ListNode(0);
            newList->next = head;
            head = newList;
           while(head->next != NULL && head->next->next != NULL){
               ListNode *p1 = head -> next;//取出第一个节点结点 
               ListNode *p2 = head -> next -> next;//取出第二个节点结点
               // head->p1->p2->...  ---->> head->p2->p1->...
               head -> next = p2;
               p1 -> next = p2 -> next;
               p2 -> next = p1;
               //move head to p1
               head = p1;
           }
           return newList->next;
        }
    };
  • 相关阅读:
    JetBrains下载历史版本
    php入门笔记
    Ajax获取服务器信息
    Ubuntu上安装PHP环境-mysql+apache+php-Linux操作系统
    Ubuntu彻底删除/卸载mysql,php,apache
    轻松理解JS基本包装对象
    JS事件委托
    浅谈JS事件冒泡
    JS闭包那些事
    浅谈JS的变量提升
  • 原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779755.html
Copyright © 2011-2022 走看看