您的位置:首页 > Web前端 > Node.js

LeetCode 24 - Swap Nodes in Pairs

2015-05-24 08:55 399 查看

一、问题描述

Description:

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
.

Note:

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

给一个链表,交换每两个相邻的结点,返回新链表。

二、解题报告

解法一:操作值域

直接交换结点的
val
是最简单的:

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL)
return NULL;
ListNode* first = head;
ListNode* second = head->next;
while(first!=NULL && second!=NULL) {
int temp = first->val;      // 交换val
first->val = second->val;
second->val = temp;
if(first->next!=NULL)
first = first->next->next;
if(second->next!=NULL)
second = second->next->next;
}
return head;
}
};


解法二:操作结点

题目要求:You may not modify the values in the list, only nodes itself can be changed. 好吧,那就来操作结点吧。

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL)
return NULL;
ListNode* first = head;
ListNode* second = head->next;
ListNode* p = new ListNode(0);
head = p;
while(first!=NULL && second!=NULL) {
ListNode* temp1 = first;
ListNode* temp2 = second;
if(second->next!=NULL)
second = second->next->next;
if(first->next!=NULL)
first = first->next->next;
p->next = temp2;
p->next->next = temp1;
p = p->next->next;
p->next = NULL;
}
if(first!=NULL) {
p->next = first;
}
return head->next;
}
};


空间复杂度为O(1)。

LeetCode答案源代码:https://github.com/SongLee24/LeetCode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode linkedlist swap