24. 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.
题目描述:
给定一个数组链表,将数组链表中的元素两两交换位置。
解题思路:
因为需要将链表元素两两交换,所以在这里我先获取到链表的前2个元素(如果链表元素不少于2)。然后在一个while循环里面,先将当前获取到的两个元素交换,然后再尝试获取下一个元素,
- 如果后面已经没有元素了,就返回;
- 如果还存在下一个元素,那么就尝试获取下下个元素;
- 如果没有,也可以直接返回,因为后面剩下一个元素,已经不能进行交换了;
- 如果还存在元素,那么就获得了后面的2个元素进行下一步的处理。
代码:
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void PrintList(ListNode* l) {
if (l == NULL) {
return;
}
ListNode* currentNode = l;
while (currentNode != NULL) {
if (currentNode != l) {
cout << "->" ;
}
cout << currentNode->val;
currentNode = currentNode->next;
}
cout << endl;
}
ListNode* Convert2ListNode(string val) {
if (val == "") {
return NULL;
}
ListNode* l = new ListNode(val[0] - '0');
ListNode* start = l;
std::string::iterator it = val.begin() + 1;
for(; it != val.end(); it++) {
l->next = new ListNode(*it - '0');
l = l->next;
}
return start;
}
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL) {
return NULL;
}
if (head->next == NULL) {
return head;
}
ListNode* start = head->next;
ListNode* node0 = head;
ListNode* node1 = head->next;
while(node1) {
ListNode* temp = node1->next;
node1->next = node0;
node0->next = temp;
if (temp == NULL || temp->next == NULL) break;
node0->next = temp->next;
node0 = temp;
node1 = temp->next;
}
return start;
}
};
int main(int argc, const char * argv[]) {
Solution sln;
ListNode* l = Convert2ListNode("1234");
PrintList(sln.swapPairs(l));
std::cout << "Hello, World!\n";
return 0;
}