C语言链表释放内存(栈溢出)
我写了一个链表,先接受指令个数m,再依次接受指令,1. APPEND <x>, 将<x>放到序列的末尾。
2. INSERT <pos> <x>, 将<x>放到序列的第<pos>个位置,位置从0开始计算。
如果<pos>小于零,或者大于序列的长度则忽略该操作。
3. DELETE <pos>, 删除第<pos>个位置的元素,位置从0开始计算。如果<pos>不合法则忽略该操作。
4. GET <pos>, 获取第<pos>个位置的元素将其输出。如果<pos>不合法则输出-1。
5. CLEAR, 清空序列。
并且要释放内存。
我写完总是内存溢出
程序代码:#include<stdio.h>
#include<stdlib.h>
struct number {
int num;
struct number *next;
};
int len(struct number **head) {//链表长度
int len;
struct number *temp = *head;
for (len = 0; temp != NULL; len++){
temp = temp->next;
}
return len;
}
void append(struct number **head,int x) {
struct number *new = (struct number *)malloc(sizeof(struct number));
new->num = x;
new->next = NULL;
while (*head != NULL) {
head = &((*head)->next);
}
*head = new;
}
void insert(struct number **head,int pos, int x) {
if (pos<0 || pos>len(head)) {
return;
}
if (pos == len(head)) {
append(head, x);
return;
}
if (pos == 0) {
struct number *new = (struct number *)malloc(sizeof(struct number));
new->num = x;
new->next =*head;
*head = new;
return;
}
struct number *new= (struct number *)malloc(sizeof(struct number));
struct number *temp,*a;
temp = *head;
a = *head;
new->num = x;
int cnt = pos;
while (--cnt) {
a = a->next;
}
cnt = pos;
while (cnt--) {
temp = temp->next;
}
a->next = new;
new->next = temp;
}
void Del(struct number **head, int pos) {
if (pos<0 || pos>=len(head)) {
return;
}
if (pos == 0) {
struct number *temp = *head;
(*head) = (*head)->next;
free(temp);
return;
}
struct number *temp=*head;
struct number *front= *head, *behind = *head;
int cnt = pos;
while (cnt--) {
temp = temp->next;//删除 的
}
cnt = pos;
while (--cnt) {//删除前面的
front = front->next;
}
cnt = pos + 1;
while (cnt--) {
behind = behind->next;
}
front->next = behind;
free(temp);
}
void Get(struct number **head,int pos) {
if (pos<0 || pos>len(head)) {
printf("-1\n");
return;
}
struct number *temp = *head;
while (pos--) {
temp = temp->next;
}
printf("%d\n", temp->num);
}
void clear(struct number **head) {
struct number * temp = *head;
struct number * ttemp;
*head = NULL;//指针设为空
while (temp != NULL)//释放
{
ttemp = temp;
temp = temp->next;
free(ttemp);
}
}
int main() {
struct number *head;//头指针
struct number **gg;
head = NULL;
gg = &head;
int cnt, pos, x;
char word[10];
scanf("%d", &cnt);
getchar();
for(int i=0;i<cnt;i++){
scanf("%s", word);
switch (word[0])
{
case 'A':{//将<x>放到序列的末尾
scanf("%d", &x);
append(gg, x);
break;
}
case 'I': {//将<x>放到序列的第<pos>个位置,位置从0开始计算
scanf("%d %d", &pos, &x);
insert(gg,pos,x);
break;
}
case 'D': {//删除第<pos>个位置的元素,位置从0开始计算。如果<pos>不合法则忽略该操作
scanf("%d", &pos);
Del(gg,pos);
break;
}
case 'G': {//获取第<pos>个位置的元素将其输出。如果<pos>不合法则输出-1
scanf("%d", &pos);
Get(gg,pos);
break;
}
case 'C': {// 清空序列
clear(gg);
break;
}
default:
break;
}
getchar();
}
clear(gg);
free(head);
return 0;
}

