程式員面試寶典之資料結構基礎----迴圈鏈表(約瑟夫環問題)

來源:互聯網
上載者:User

關於迴圈鏈表,即單鏈表的為指標指向頭結點,當然在建立迴圈鏈表的時候可以將鏈表的為指標指向頭結點,但本例用的是先建立一個只有一個節點的迴圈鏈表(即next指標指向自己結點),然後再在此迴圈鏈表中插入節點,實現最終的迴圈鏈表(見代碼),這裡我預設指定了一個“偽頭結點”的節點(即剛開始建立的節點),即使在後面尋找第K個節點的時候也是用到了這個“偽頭結點”。


#include <iostream>#include <stdio.h>#include <stdlib.h>#define NUM 0;using namespace std;//約瑟夫環問題,關鍵是建立迴圈鏈表(即建立約瑟夫環)typedef struct Node{    int data;    struct Node *next;}node;void Josephus(int n, int k, int m)//n為約瑟夫環中的中人數,k為第一個開始報數的人,m為出列者喊到的數{    node* p ;    node* report;    //node* head;    node* curr;    //creat the circulate list    //追加節點法    //先建立一個只有一個節點的迴圈鏈表p,然後用迴圈逐漸往裡追加節點。    p = (node*)malloc(sizeof(node));    p->data = 1;    p->next = p;    curr = p;    for(int i = 2;i <= n;i++)    {        node* t = (node*)malloc(sizeof(node));        t->data = i;        t->next = curr->next;        curr->next = t;        curr = t;    }    //找到第一個報數的人,把curr節點移到這個人    report = curr->next; //此時的curr->next相當於鏈表的第一個節點,即標號為1的節點(偽頭結點)    //找到第k個節點    for(int j = 1; j < k ;j++)    {        report = p;        p = p->next;    }    //依次找到出列者並刪除    while(n--)    {        for(int s = m-1; s >0 ; s--)        {            report = p;            p = p->next;        }        report->next = p->next;        printf("%d->",p->data);        free(p);        p = report ->next ;    }}int main(){    Josephus(15,6,2);    return 0;}


輸出結果:

7->9->11->13->15->2->4->6->10->14->3->8->1->12->5->
Process returned 0 (0x0)   execution time : 2.293 s
Press any key to continue.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.