1、双链表的建立、测长、打印
typedef struct dnode { int data; struct dnode* prior; struct dnode* next; }dnode; //双链表建立 dnode* Create(dnode *head, int n) { dnode *p = head; dnode* q; for(int i=0; i<n; i++) { q = (dnode*)malloc(sizeof(dnode)); cin >> q->data; q->prior = p; p->next = q; p = q; } p->next = NULL; return head; } //双链表长度 int Len(dnode* head) { dnode *p = head; int len = 0; while(p->next != NULL) { p = p->next; len ++; } return len; } //双链表打印 void Print(dnode *head) { dnode *p = head; while(p->next != NULL) { p = p->next; cout << p->data << " "; } cout << endl; }
2、删除第i个位置上的元素
找到第i个位置p,p->prior->next = p->next; p->next->prior = p->prior
//删除第i个位置上的元素 dnode *Delete(dnode *head, int i) { dnode *p = head; dnode *q; int j = 0; while(p &&j<i) { p = p->next; j++; } if(!p|| (j>i)) return head; p->prior->next = p->next; p->next->prior = p->prior; return head; }
3、在第i个位置插入元素
找到第i个位置元素p,在p前面插入q,q->next = p; q->prior = p->prior; p->prior->next = q; p->prior = q;
//在第i个位置插入元素 dnode *Insert(dnode *head, int i) { dnode *p = head; dnode *q; int j = 0; while(p && (j<i)) { p = p->next; j++; } if(!p || (j>i)) return head; q = (dnode*)malloc(sizeof(dnode)); cin >> q->data; q->next = p; q->prior = p->prior; p->prior->next = q; p->prior = q; return head; }
4、约瑟夫环
已知n个人(编号0,1,2,3...n-1)围坐在一张圆桌周围,从编号为k的人开始报数,数到m的那个人出列,他的下一个又从0开始报数,数到m的人出列,以此进行下去,直到全部出列。
要使用循环单链表
typedef struct node { int data; struct node *next; }node; //n为人数;k为第一个开始报数的人;m为出列喊到的数 void Josephus(int n, int k, int m) { //建立循环单链表 node *p = (node*)malloc(sizeof(node)); p->data = 0; p->next = p; node *r = p; for(int i=1; i<n; i++) { node *q = (node*)malloc(sizeof(node)); q->data = i; q->next = r->next; r->next = q; r = q; } while(k--) { r = p; p = p->next; } while(n--) { for(int s = m; s--; r = p, p = p->next); r->next = p->next; cout << p->data << " "; free(p); p = r->next; } }