基于Visual C++2013拆解世界五百强面试题--题14-循环删除

来源:互联网 发布:锐捷网络怎么登录 编辑:程序博客网 时间:2024/05/21 06:11

有一个数组a[1000]存放0-1000,要求每隔二个数删除一个数,到末尾时循环到开头继续进行,求最后一个被删掉数的原始下标。


看到题目可以用循环链表保存这些数,然后循环删除,大大减少了一些复杂的边界判断。


下面上代码,看链表建立和删除的具体过程:


#include <stdio.h> #include <stdlib.h>typedef struct stLIST{int index;stLIST *next;}LIST, *PLIST;//创建循环链表PLIST CreateRoundList(int size){PLIST head = NULL;PLIST temp = (PLIST)malloc(sizeof(LIST));temp->index = 0;temp->next = NULL;head = temp;for (int i = 1; i < size; i++){temp->next = (PLIST)malloc(sizeof(LIST));temp = temp->next;temp->index = i;temp->next = NULL;}//尾部指向头部,构造循环链表temp->next = head;return head;}PLIST DeleteNode(PLIST head){//判断是否只有一个节点了while (head != head->next){//指向head的下一个节点head = head->next;//保存要删除节点的指针PLIST temp = head->next;//删除节点head->next = head->next->next;free(temp);//指向刚才删除的节点的下一个节点head = head->next;//继续循环}return head;}int main(){PLIST head = CreateRoundList(1000);printf("剩下的数的下标:%d\n", DeleteNode(head)->index);return 0;}

运行结果:




如果有什么问题和疑问可以在下面留言互相探讨。

原题我已经上传到这里了http://download.csdn.net/detail/yincheng01/6461073 ,

解压密码为 c.itcast.cn



原创粉丝点击