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.

【题意】

给定一个链表,交换每两个相邻的节点,并返回它的头。

你的算法应该使用常数空间。您不得修改在列表中的值,只有节点本身是可以改变的。

【分析】

【代码】

/*********************************
*   日期:2014-01-29
*   作者:SJF0115
*   题号: Swap Nodes in Pairs
*   来源:http://oj.leetcode.com/problems/swap-nodes-in-pairs/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if (head == NULL){
            return head;
        }

        ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;

        ListNode *nodeA,*nodeB = NULL;

        ListNode *pre = dummy,*cur = head;
        //至少2个节点采用交换
        while(cur != NULL && cur->next != NULL){
            nodeA = cur;
            nodeB = cur->next;
            //交换
            nodeA->next = nodeB->next;
            nodeB->next = nodeA;
            pre->next = nodeB;
            //更新pre,cur
            pre = nodeA;
            cur = nodeA->next;
        }
        return dummy->next;
    }
};
int main() {
    Solution solution;
    int A[] = {1,2,3,4,5};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 4;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.swapPairs(head->next);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    return 0;
}


LeetCode之Swap Nodes in Pairs

上一篇:IIS首次发布VS2012创建的web应用程序时注册.net4.0


下一篇:WebRTC音视频引擎研究(2)--VoiceEngine音频编解码器数据结构以及参数设置