【发布时间】:2021-03-24 11:15:03
【问题描述】:
我的程序触发了一个断点,我认为算法很好。我想删除链表或队列中的第一个节点,无论如何。关键是我通常可以将元素添加到堆栈中,但不能删除它们,因为它会触发断点。为什么?我想在不使用前后指针的情况下删除第一个元素。那可能吗? 我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#define MAX 100
#define MIN 10
typedef struct node* Queue;
struct node {
int el;
Queue next;
};
void push(int x, Queue S);
void pop(Queue S);
void show(Queue S);
int main() {
int sl;
char c;
struct node Head;
Head.next = NULL;
srand(time(0));
while (1) {
printf("Queue\n\t->D to push\n\t->I to pop\n\t\n\t->E for exit\n\t->Choice: ");
scanf("%c", &c);
switch (c) {
case'd':
case'D':
sl = MIN + rand() % ((MAX - MIN) + 1);
push(sl, &Head);
show(Head.next);
break;
case'i':
case'I':
pop(&Head);
printf("After pop:\n");
show(Head.next);
break;
case'e':
case'E':
return 0;
break;
default:
printf("A mistake has occured.\n");
}
}
return 0;
}
void push(int x, Queue S) {
Queue q;
q = (Queue)malloc(sizeof(struct node));
q->el = x;
q->next = S->next;
S->next = q;
}
void pop(Queue S) {
Queue temp,pre;
temp = S->next;
pre=NULL;
while(temp && temp->next) {
pre = temp;
temp = temp->next;
}
free(pre->next);
pre->next = NULL;
}
void show(Queue S) {
while (S != NULL)
{
printf("%d", S->el);
S = S->next;
printf("\n");
}
}
【问题讨论】:
标签: c linked-list queue