生活随笔
收集整理的這篇文章主要介紹了
带头节点循环链表实现队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
隊列的特征就是“先入先出”,入隊時在鏈表的尾部插入數(shù)據(jù),出隊時刪除掉頭節(jié)點后面的節(jié)點,需要一個尾指針,始終指向鏈表的尾部(新加進(jìn)來的節(jié)點)。具體請看原理圖:
代碼實現(xiàn)
#include <stdio.h>
#include <stdlib.h>typedef struct List
{int data
; struct List
*next
;
}ListNode
; ListNode
*rear
; void Init(ListNode
*head
);
void push(ListNode
*head
, int data
);
void pop(ListNode
*head
);
void print(ListNode
*head
); int main()
{ListNode head
;Init(&head
);push(&head
, 1);print(&head
);pop(&head
);print(&head
);pop(&head
);print(&head
);system("pause");return 0;
}void Init(ListNode
*head
)
{head
->data
= 0;head
->next
= head
;rear
= head
;
}void push(ListNode
*head
,int data
)
{ListNode
*tem
= (ListNode
*)malloc(sizeof(ListNode
));if (tem
== NULL){printf("創(chuàng)建新節(jié)點失敗,入隊失敗");return;}rear
->next
= tem
; tem
->data
= data
;tem
->next
= head
; rear
= tem
;
}void pop(ListNode
*head
)
{if (head
->next
== head
){printf("隊內(nèi)無元素,出隊錯誤\n");return;}ListNode
*tem
= head
->next
;head
->next
= tem
->next
; printf("出隊元素: %d\n", tem
->data
);if (tem
->next
== head
){rear
= head
; }free(tem
);tem
=NULL;
}void print(ListNode
*head
)
{ListNode
*tem
= head
->next
;if (tem
== head
){printf("當(dāng)前隊列無元素\n");return;}for (; tem
!= head
; tem
= tem
->next
){printf("%d ", tem
->data
);}printf("\n");
}
總結(jié)
以上是生活随笔為你收集整理的带头节点循环链表实现队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。