链表实现从一维数组中每次随机选择两个不同下标数组元素的值打印,已经打印的数组序列不再打印。
初始化:
picNode* initNode(picNode* head, int* a)
{
a = (int*)malloc(20 * sizeof(int));
for (int i = 0; i < 20; i++)
{
a[i] = i + 1;
}
head = malloc(sizeof(picNode));
picNode* markhead = head;
head->num = 0;
head->next = NULL;
for (int i = 0; i < 20; i++)
{
picNode* tmp = malloc(sizeof(picNode));
head->next = tmp;
tmp->num = a[i];
tmp->next = NULL;
head = tmp;
}
picNode* setmp = markhead;
while (setmp->next!=NULL)
{
printf("%d\t", setmp->next->num);
setmp = setmp->next;
}
printf("\n");
return markhead;
}
查找和删除节点:
picNode* searchNum(picNode* head,int len,int* k)
{
int a = 0;
int b = 0;
srand((unsigned)time(NULL));
while (a==b)
{
a = rand() % (len-1);
b = rand() % (len - 1);
}
int i = 0;
picNode* pre = head;
picNode* cur = pre->next;
while (i<a)
{
cur = cur->next;
pre = pre->next;
i++;
}
pre->next = cur->next;
k[0] = cur->num;
free(cur);
pre = head;
cur = pre->next;
i = 0;
while (i < b)
{
cur = cur->next;
pre = pre->next;
i++;
}
pre->next = cur->next;
k[1] = cur->num;
free(cur);
return head;
}
释放内存:
int memDestory(picNode* head, int* a)
{
free(head);
free(a);
return 0;
}
主函数:
int main()
{
picNode* head = NULL;
int *a = NULL;
int b[2] = { -1,-1 };
head = initNode(head, a);
int len = 20;
while (len!=0)
{
head = searchNum(head, len-=2, b);
printf("%d\t%d\n", b[0], b[1]);
}
memDestory(head, a);
return 0;
}