我很搞笑的用C++写了个C版本的双向循环链表(虽然是超时的,但是很久没有写过链表的,所以试一试)。。。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node {
int num;
struct node * pre, * next;
};
struct node * create(struct node * head, int n) {
struct node * p, * q;
for(int i = 1; i <= n; i++) {
q = (struct node *)malloc(sizeof(struct node));
q->num = i;
if(head == NULL) { //head为空 还没有节点。
head = q;
q->next = q;
q->pre = q;
}
else { //p后面加了q
q->next = p->next;
q->pre = p;
p->next->pre = q;
p->next = q;
}
p = q;
}
return p->next; //返回第一个节点
}
struct node * solve(struct node * head, int time) {
struct node * p, * q;
int cnt = 1;
p = q = head->pre;
while(cnt <= time) {
p = p->next;
cnt++;
}
p->next->pre = p->pre;
p->pre->next = p->next;
q = p->next;
free(p);
return q;
}
/*
void Print(struct node * head, int m) {
struct node * p;
for(int i = 1; i <= m; i++) {
p = p->next;
}
}
*/
int main() {
int cas; cin >> cas;
while(cas--) {
int N; cin >> N;
struct node * head = NULL;
head = create(head, N);
for(int i = 1; i < N; i++) head = solve(head, i);
cout << head->num << endl;
}
return 0;
}
本文介绍了一个使用C++编写的双向循环链表的实现案例。该案例通过手动创建节点并连接它们来构建链表,并提供了解决方案以进行基本操作。尽管此实现可能不是最高效的,但对于理解链表的基本概念和操作仍具有一定价值。
627

被折叠的 条评论
为什么被折叠?



