File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change @@ -1277,6 +1277,95 @@ impl MyStack {
12771277}
12781278```
12791279
1280+ ### C:
1281+
1282+ > C:单队列
1283+
1284+ ``` c
1285+ typedef struct Node {
1286+ int val;
1287+ struct Node *next;
1288+ } Node_t;
1289+
1290+ // 用单向链表实现queue
1291+ typedef struct {
1292+ Node_t *head;
1293+ Node_t *foot;
1294+ int size;
1295+ } MyStack;
1296+
1297+ MyStack* myStackCreate () {
1298+ MyStack *obj = (MyStack *)malloc(sizeof(MyStack));
1299+ assert (obj);
1300+ obj->head = NULL;
1301+ obj->foot = NULL;
1302+ obj->size = 0;
1303+ return obj;
1304+ }
1305+
1306+ void myStackPush (MyStack* obj, int x) {
1307+
1308+ Node_t *temp = (Node_t *)malloc(sizeof(Node_t));
1309+ assert(temp);
1310+ temp->val = x;
1311+ temp->next = NULL;
1312+
1313+ // 添加至queue末尾
1314+ if (obj->foot) {
1315+ obj->foot->next = temp;
1316+ } else {
1317+ obj->head = temp;
1318+ }
1319+ obj->foot = temp;
1320+ obj->size++;
1321+ }
1322+
1323+ int myStackPop(MyStack* obj) {
1324+
1325+ // 获取末尾元素
1326+ int target = obj->foot->val;
1327+
1328+ if (obj->head == obj->foot) {
1329+ free(obj->foot);
1330+ obj->head = NULL;
1331+ obj->foot = NULL;
1332+ } else {
1333+
1334+ Node_t *prev = obj->head;
1335+ // 移动至queue尾部节点前一个节点
1336+ while (prev->next != obj->foot) {
1337+ prev = prev->next;
1338+ }
1339+
1340+ free(obj->foot);
1341+ obj->foot = prev;
1342+ obj->foot->next = NULL;
1343+ }
1344+
1345+ obj->size--;
1346+ return target;
1347+ }
1348+
1349+ int myStackTop(MyStack* obj) {
1350+ return obj->foot->val;
1351+ }
1352+
1353+ bool myStackEmpty(MyStack* obj) {
1354+ return obj->size == 0;
1355+ }
1356+
1357+ void myStackFree(MyStack* obj) {
1358+ Node_t * curr = obj->head;
1359+ while (curr != NULL) {
1360+ Node_t * temp = curr->next;
1361+ free(curr);
1362+ curr = temp;
1363+ }
1364+ free(obj);
1365+ }
1366+
1367+ ```
1368+
12801369
12811370<p align="center">
12821371<a href="https://programmercarl.com/other/kstar.html" target="_blank">
You can’t perform that action at this time.
0 commit comments