题目:Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
C++代码:
#include <iostream>
#include <vector>
using namespace std;
//构造节点
struct Node {
int element = 0;
Node* next = NULL;
};
//打印一个链表
void print(Node* header) {
while(header->next != NULL) {
cout << header->element << " ";
header = header->next;
}
cout << endl;
}
//创建一个链表
Node* createList(vector<int> m, Node * header) {
unsigned long count = m.size();
Node* temp ;
Node* p = new Node();
p->next = header;
for(int i = 0; i < count; i++) {
header->element = m[i];
temp = new Node();
header->next = temp;
header = temp;
}
return p->next;
}
//负责交换的代码
Node* swapList(Node* header) {
Node* p = new Node();
p->next = header;
Node* p1;
Node* p2;
Node* temp1;
Node* temp2 = p;
while(header->next != NULL) {
p1 = header;
p2 = header->next;
temp1 = p2->next;
p2->next = p1;
p1->next = temp1;
temp2->next = p2;
temp2 = temp2->next->next;
header = temp1;
}
return p->next;
}
int main() {
int n;
cout << "请输入节点的个数(偶数)" << endl;
cin >> n;
vector<int> m;
int x;
for(int i = 0; i < n; i++) {
cin >> x;
m.push_back(x);
}
Node* header = new Node();
header = createList(m, header);
header = swapList(header);
print(header);
}
最后
以上就是隐形小蜜蜂最近收集整理的关于交换链表的奇偶位(比如1和2,3和4,5和6。。。交换)的全部内容,更多相关交换链表内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复