LeetCode-24-两两交换链表中的节点
/*两两交换链表中的节点*/
#include<iostream>
using namespace std;
struct Node{
int val;
Node *next;
};
Node *create(Node *head,int n){//构建链表
int num;
Node *tail = head;
for (int i = 0; i < n; i++){
cin >> num;
Node *cur = new(Node);
cur->val = num;
cur->next = NULL;
if (head == NULL){
head = cur;
tail = cur;
}
else{
tail->next = cur;
tail = cur;
}
}
return head;
}
Node * swap(Node *head){//两两交换
Node *pre = head, *cur,*pos=NULL,*fore=NULL;
if (head->next != NULL){
pos = pre->next;
}
else{
return head;
}
if (pre == head){
cur = pos->next;
pos->next = pre;
head=pos;
fore = pre;
pre = cur;
if (pre == NULL){//偶数个
fore->next = NULL;
return head;
}
else{
pos = cur->next;
if (pos == NULL){//奇数个
fore->next = cur;
return head;
}
}
}
//两两交换
while (pos != NULL){
fore->next = pos;
cur = pos->next;
pos->next = pre;
fore = pre;
pre = cur;
if (pre == NULL){//偶数个
fore->next = NULL;
break;
}
else{
pos = cur->next;
if (pos == NULL){//奇数个
fore->next = cur;
break;
}
}
}
return head;
}
int main(){
int n;//链表长度
cin >> n;
Node *head = NULL, *tail = NULL;
head = create(head, n);
head = swap(head);
//输出链表
while (head != NULL){
cout << head->val << ' ';
head = head->next;
}
cout << endl;
return 0;
}