在结点类型为DLinkNode的带头结点的双链表L中给出将p所指结点(非尾结点)与其后继结点交换的算法。
代码#include
using namespace std;
typedef struct DNode {
DNode* pr;
DNode* next;
int data;
}DLinkNode;
void CreateList(DLinkNode*& L,int a[],int n) {
DLinkNode* s, * r;
L = new DLinkNode;
r = L;
for (int i = 0; i < n; i++) {
s = new DLinkNode;
s->data = a[i];
r->next = s;
s->pr = r;
r = s;
}
r->next = NULL;
cout << "双链表创建成功!" << endl;
}
void DispList(DLinkNode* L) {
cout << "双链表元素为:" ;
DLinkNode* p = L->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void ChangeNode(DLinkNode*& L, int j) {
DLinkNode* p = L;
int i = 0;
while (i < j && p != NULL) {
i++;
p = p->next;
}
if (p == NULL) { cout << "该结点不存在!" << endl; }
else if (p->next == NULL) { cout << "该结点的后继结点不存在!" << endl; }
else {
DLinkNode* q = p->next;
p->pr->next = q;
p->next = q->next;
q->next = p;
}
cout << "交换成功!" << endl;
}
int main() {
DLinkNode* p;
int n; int j;
cout << "请输入双链表元素个数:" ;
cin >> n;
int* a = new int[n];
srand(time(NULL));
for (int i = 0; i < n; i++) {
a[i] = rand() % (15 - 1 + 1) + 1;
}
CreateList(p,a,n);
DispList(p);
cout << "请问将第几个结点及其后继结点交换?";
cin >> j;
ChangeNode(p, j);
DispList(p);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)