数组实现链表:
#include<stdio.h> #include<stdlib.h> #define N 8 #define M 5 int item[N]; int next[N]; void init() { int i; for(i=0;i<N;i++) { item[i]=i; next[i]=i+1; } //设置循环 next[N-1]=0; } void printArray(int index) { int head = index; do{ printf("%d->",item[index]); index=next[index]; }while(index!=head); printf("\n"); } int main() { init(); int only=0; int i=1; printArray(only); while(only!=next[only]) { for(i=1;i<M-1;i++) only=next[only]; printf("out %d \n",item[next[only]]); next[only]=next[next[only]]; only=next[only]; printArray(only); } return 0; }
指针链表:
#include<stdio.h> #include<stdlib.h> struct Node { int item; struct Node* next; }; void printList(struct Node* h) { struct Node* x=h; do { printf("%d->",x->item); x=x->next; }while(x!=h); printf("\n"); } int main(int argc,char* argv[]) { int i=0; if(argc!=3) exit(0); int N=atoi(argv[1]); int M=atoi(argv[2]); //初始化第一个元素 struct Node* t = (struct Node*)malloc(sizeof(struct Node*)); t->item=0; t->next=t; struct Node* head = t; //初始化剩余元素 for(i=1;i<N;i++) { struct Node* n = (struct Node*)malloc(sizeof(struct Node*)); n->item=i; n->next=head; t->next=n; t=n; } printList(head); struct Node* x=head; //yuesefu while(x != x->next) { int i; for(i=1;i<M-1;i++) x=x->next; struct Node* del=x->next; x->next=del->next; x=x->next; printf("out %d\n",del->item); free(del); printList(x); } }