3 条题解
-
3
C语言双向链表写法 (虚拟头尾节点)
#include <stdlib.h> #include <stdio.h> typedef struct _List { struct _List *pr; int num; struct _List *ne; } List; //节点结构体 int n; List *head, *tail; //头节点、尾节点指针 void init() { head = (List*)malloc(sizeof(List)); tail = (List*)malloc(sizeof(List)); head -> pr = NULL; head -> ne = tail; tail -> pr = head; tail -> ne = NULL; } //链表初始化 void insert_to_tail(int x) { List *temp = (List*)malloc(sizeof(List)); temp -> pr = tail -> pr; temp -> num = x; temp -> ne = tail; tail -> pr -> ne = temp; tail -> pr = temp; } //在尾部新增节点 void earse(List *temp) { temp -> pr -> ne = temp -> ne; temp -> ne -> pr = temp -> pr; } //删除节点 int main() { scanf("%d", &n); init(); for(int i = 1; i <= n; i++) { insert_to_tail(i); } int rec = 1, flag = 1; //rec计数,flag标记方向 List *temp = head -> ne; while(n) { if(n == 2 && rec == 1) { //剩下两个人报1结束 printf("\n%d\n", temp -> num); break; } if(rec == 3) { //踢人 printf("%d ", temp -> num); earse(temp); n--; } if(flag && temp -> ne == tail) flag = 0; if(!flag && temp -> pr == head) flag = 1; //转换方向 flag ? temp = temp -> ne : temp = temp -> pr; //下一个人 rec = rec % 3 + 1; //报数 } return 0; }
信息
- ID
- 102
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 7
- 标签
- 递交数
- 145
- 已通过
- 36
- 上传者