数据结构——带头节点的约瑟夫问题学习笔记
链表使用的是带头节点的双向循环链表:
//system.h: Status InitList(DuLinkList &L){ L = (DuLinkList)malloc(sizeof(DuLNode)); DuLinkList q,p; L->next = L; L->prior = NULL; q=L; int n; cout<<"输入人数n:"; cin>>n; for(int i=0; i<n; i++){ p=(DuLinkList)malloc(sizeof(DuLNode)); p->data=i+1; q->next = p; p->prior = q; p->next = L; L->prior = p; q=p; } return OK; }
Status OutputList(DuLinkList L){ DuLinkList p=L; cout<<" "; while(p->next!=L){ p = p->next; cout<<p->data<<" "; } cout<<endl; return OK; }
int GetLeghtList(DuLinkList L){ DuLinkList q=L; int i=0; while(q->next!=L){ i++; q = q->next; } return i; }
Status DeleteList(DuLinkList &L,int k,int m){ DuLinkList p=L->next,s; int j=1,i=1,total,n; while((p->next)!=L&&j<k){ p = p->next; j++; } if(k!=GetLeghtList(L)) if((p->next)==L || j>k)return ERROR; total = GetLeghtList(L); while (total != 1) { for (int t = 1; t < m; t++){ if(p->next==L) p=L->next; else
p = p->next;
} cout<<"第"<<p->data<<"个人出列,"; s = p; if(p->next==L){ p=L->next; s->prior->next = L; L->prior = s->prior; } else { p=s->next; p->prior = s->prior; s->prior->next = p; } free(s); n=GetLeghtList(L); cout<<"还有"<<n<<"人。"<<endl; total--; } cout<<"最后一人是第"<<p->data<<"个人!"; return OK;
}
//define.h: #include <iostream.h> #include <stdlib.h> #include <stdio.h> #include <malloc.h> #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2
//function.h: typedef int ElemType; typedef int Status; typedef struct DuLNode{ ElemType data; struct DuLNode *prior; struct DuLNode *next; }DuLNode,*DuLinkList;
// 主函数: #include "define.h" #include "function.h" #include "system.h" int main(int argc, char *argv[]) { ElemType k,m; DuLinkList t; InitList(t); OutputList(t); cout<<"输入k,m:"; cin>>k>>m; DeleteList(t,k,m); return 0; }