雙向鍊錶和迴圈鍊錶並用

2021-10-16 08:10:32 字數 2329 閱讀 5144

雙向鍊錶使用前驅指標以及後繼指標

迴圈鍊錶就是尾指標指向頭

約瑟夫環問題:n個人圍成乙個圈,指定乙個數字v,從第乙個人開始報數,每輪報到v的選手出局,由下乙個人接著從頭開始報,最後乙個人是贏家。其中n>1,v>2。

下面是迴圈鍊錶(單向)在約瑟夫環中的應用,測試資料只用了615,答案是546231,可能程式還有其他錯誤,望指正。

以下變數中:n是總人數,s是第幾個人,最後乙個程式預設s是1,v是指定數字即迴圈次數;

#include

#include

/*單向的話需要兩個指標,雙向的話,乙個指標就夠了*/

struct s

;int count=0;

struct s*

create

(int n)

else

p=((

struct s*

)malloc

(sizeof

(struct s)))

; p->m=count+1;

} pend->next=phead;

return phead;

}int

main

(void

) p=p0->next;

a[j]

=p->m;j++

; p0->next=p->next;

p=p0->next;

n--;}

for(i=

0;i)printf

("%d "

,a[i]);

}

下面是迴圈鍊錶(雙向)在約瑟夫環的應用,測試資料只用了615,答案是546231,程式可能還有其他錯誤,若有不當請指正

#include

#include

struct s

;int count=0;

struct s*

create

(int n)

else

p=((

struct s*

)malloc

(sizeof

(struct s)))

; p->m=count+1;

} pend->next=phead;

phead->prior=pend;

return phead;

}int

main

(void

),j=

0,i;

struct s*p;

scanf

("%d%d%d"

,&n,

&s,&v)

; p=

create

(n);

while

(n>0)

a[j]

=p->m;j++

; p->prior->next=p->next;

p->next->prior=p->prior;

/*雙向鍊錶刪除乙個節點時,修改後繼指標的時候也要把前驅指標給修改了*/

p=p->next;

n--;}

for(i=

0;i)}

下面是沒有鍊錶的迴圈程式,個人認為還比較簡單,不用鍊錶也沒有十分繁瑣,主要涉及到陣列中的座標問題,其餘的不是很複雜

測試資料只有615,答案是546231,若有不當請指正

#include

void

del(

int a,

int n,

int i)

;int

main

(void

),b[

100]=;

scanf

("%d%d%d"

,&n,

&s,&m)

; t=n;

for(i=

0;i)for

(c=m+s-

2;j)for

(i=0

;i)return0;

}void

del(

int a,

int n,

int i)

}

注,陣列刪除元素:

1.字元陣列刪除元素每次刪除乙個到了末尾讓\0往上補,\0也不會顯示出來,以此達到刪除的目的

2.整形陣列刪除時示例如下

輸入 12345678

刪除45

得到結果(若全部輸出)

為12367888,最後的數字一定會贅餘,因此要控制輸出元素個數

如果輸出的元素個數為6,則為123678,可以達到刪除元素的目的。

雙向鍊錶和雙向迴圈鍊錶

和單向鍊錶相比,多了乙個前驅結點。如果他為空,那麼next和prior都指向自己。而對於雙迴圈鍊錶,只需要最後乙個元素的next指向head next,head next的prior指向最後乙個節點即可。新節點s插入鍊錶,s next給p結點,s prior給p prior,然後,p prior n...

雙向鍊錶和迴圈鍊錶

雙向鍊錶和單鏈表的區別就在於多了乙個前驅 有需要檢視單鏈表的在主頁裡面查詢 雙向鍊錶 如下 typedef class node node class doublelist doublelist node buynode int val,node next,node pre void insert ...

迴圈鍊錶,雙向鍊錶

迴圈鍊錶 迴圈鍊錶與順序鍊錶之間的區別 迴圈鍊錶最後乙個資料的next指標域不為空,而是指向頭結點,其他基本操作大體相同,只是在判斷表結束的條件變為判斷節點的引用域是否為頭引用 雙向鍊錶 author neosong date oct 10,2017 4 43 01 pm program of in...