-
题目描述:
-
生成一个长度为21的数组,依次存入1到21;
建立一个长度为21的单向链表,将上述数组中的数字依次存入链表每个结点中;
将上述链表变为单向封闭(循环)链表;从头结点开始数,将第17个结点删除,将它的下一个结点作为新的头结点;
重复上述过程,直到该链表中只剩一个结点,显示该结点中存入的数字。
-
输入:
-
没有任何输入数据。
-
输出:
-
输出上面题目描述中最后剩下的节点中存入的数字。
#include <cstdio>
#include <cstdlib>
using namespace std;
struct List {
int value;
List *next;
};
struct List *insertList(struct List *head, int value)
{
if (head == NULL) {
head = (List*)malloc(sizeof(struct List));
head->value = value;
head->next = NULL;
}
else {
struct List *p = head;
while (p->next != NULL)
p = p->next;
struct List *p1 = (List*)malloc(sizeof(struct List));
p1->value = value;
p1->next = NULL;
p->next = p1;
}
return head;
}
void foo(struct List *head)
{
if (head == NULL)
return;
else if (head->next == NULL)
printf("%d\n", head->value);
else {
struct List *p = head;
while (p->next != NULL)
p = p->next;
p->next = head;
struct List *q;
while (p->next != p) {
for (int i = 0; i < 16; i++) {
p = p->next;
}
q = p->next;
p->next = p->next->next;
free(q);
}
printf("%d\n", p->value);
}
}
int main() {
int array[21];
int i;
for (i = 0; i < 21; i++) {
array[i] = i+1;
}
struct List *head = NULL;
for (i = 0; i < 21; i++) {
head = insertList(head, array[i]);
}
foo(head);
return 0;
}