#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<queue>
using namespace std;
//结点
typedef struct Lnode {
int data;
struct Lnode *next;
}Lnode, *Linklist;
//尾插
void Creatlist(Linklist &L, int &e) {
Lnode *p = new Lnode;
p->data = e;
p->next = NULL; //处理新加入节点
Lnode *cur = L;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = p;
p->next = NULL;
}
//初始化
void Initlist(Linklist &L) {
L = new Lnode;
L->next = NULL;
}
//交换(指定结点he前驱节点)
void Exchange(Linklist &L1,int &pos) {
Lnode *pre = L1;
Lnode *cur =pre->next;
while (pos>1&&cur!=NULL)
{
pre = pre->next;
cur = pre->next;
pos--;
}
int data = pre->data;
pre->data = cur->data;
cur->data = data; //交换节点元素值
}
//打印
void Print(Linklist &L1) {
Lnode *cur = L1->next;
while (cur->next) {
printf("%d ", cur->data);
cur = cur->next;
}
cout << cur->data << endl;
}
int main() {
int n;
while (scanf("%d",&n)!=EOF) {
if (n == 0) break;
Linklist L1;
Initlist(L1);
for (int i = 0; i < n; i++) { //输入数据
int e;
cin >> e;
Creatlist(L1, e);
}
int pos;
cin >> pos; //指定位置
Exchange(L1, pos);
Print(L1);//打印
}
}
BJFU 233双向循环链表中结点的交换
于 2023-03-13 09:41:38 首次发布