生活随笔
收集整理的这篇文章主要介绍了
带头节点循环链表实现队列
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
队列的特征就是“先入先出”,入队时在链表的尾部插入数据,出队时删除掉头节点后面的节点,需要一个尾指针,始终指向链表的尾部(新加进来的节点)。具体请看原理图:
代码实现
#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("创建新节点失败,入队失败");return;}rear
->next
= tem
; tem
->data
= data
;tem
->next
= head
; rear
= tem
;
}void pop(ListNode
*head
)
{if (head
->next
== head
){printf("队内无元素,出队错误\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("当前队列无元素\n");return;}for (; tem
!= head
; tem
= tem
->next
){printf("%d ", tem
->data
);}printf("\n");
}
总结
以上是生活随笔为你收集整理的带头节点循环链表实现队列的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。