-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslqueue.cpp
92 lines (72 loc) · 1.39 KB
/
slqueue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "slqueue.h"
void InitQueue(PSLQueue que)
{
assert(que != NULL);
que->next = NULL;
}
static Node *BuyNode(int val, int prio)
{
Node *p = (Node *)malloc(sizeof(Node));
assert(p != NULL);
p->data = val;
p->prio = prio;
p->next = NULL;
return p;
}
//返回第一个优先级低于(优先级数字大于)prio的节点的前驱
static Node *SearchPre(PSLQueue que, int prio)
{
Node *p;
for(p = que; p->next != NULL; p = p->next)
{
if(p->next->prio > prio)
break;
}
return p;
}
bool Push(PSLQueue que, int val, int prio) //O(n)
{
Node *p = BuyNode(val, prio);
Node *q = SearchPre(que, prio); //O(n)
p->next = q->next;
q->next = p;
return true;
}
bool IsEmpty(PSLQueue que)
{
return que->next == NULL;
}
bool GetTop(PSLQueue que, int *rtval)
{
if(IsEmpty(que))
return false;
*rtval = que->next->data;
return true;
}
bool Pop(PSLQueue que, int *rtval) //O(1)
{
if(IsEmpty(que))
return false;
Node *p = que->next;
*rtval = p->data;
que->next = p->next;
free(p);
return true;
}
void Clear(PSLQueue que);
{
Destroy(que);
}
void Destroy(PSLQueue que);
{
Node *p;
while(que->next != NULL)
{
p = que->next;
que->next = p->next;
free(p);
}
}