问题描述
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个节点所代表的数值顺序反转,比如:原链表为1->2->3->4->5;则每2个节点顺序翻转:2->1->4->3->5。
所以我们的思路可以分为两部分:首先将原链表每k个节点就划分;然后在k个节点内部进行顺序发展。具体过程可见代码:
代码展示
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
struct ListNode { //定义链表的结构体
int val;
ListNode*next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head){
ListNode*curr;
curr = head;
int count = 0;
while(curr != NULL && count != 2){ //从头节点开始往后找到2个节点
curr = curr->next;
count++;
}
if (count == 2) { //如果有k个节点则进行这2个节点的谁顺序变换
curr = swapPairs(curr); //从2+1节点开始,重复上过程,查找第2个2个节点
while (count-- > 0) {
ListNode*tmp = head->next; //定义节点tmp为头结点的下一个节点
head->next = curr; //使原头结点指向指向2+2节点的节点。
curr = head; //让curr表示原来的头结点
head = tmp; //此时移动头结点,使原来的第二节点变为新的头结点
} //经过一轮循环,完成了将头结点移出到另一条链表线,原第二节点变为新的头结点
head = curr;
}
return head;
}
};
int main(){
cout<<"输入链表的长度:";
int n;
cin>>n;
ListNode* head=NULL;
ListNode* p;
int a;
for(int i=0;i<n;i++){
cin>>a;
if (head == NULL){
head = (ListNode *)malloc(sizeof(ListNode));
head->val = a;
p = head;
}
else{
p->next = (ListNode *)malloc(sizeof(ListNode));
p = p->next;
p->val = a;
}
}
p->next=NULL;
Solution solution;
ListNode* result = solution.swapPairs(head);
while(result!=NULL){
cout<<result->val<<" ";
result=result->next;
}
cout<<endl;
return 0;
}
运行结果截图