【每日算法】AB9 链表

题目

描述

请你实现一个链表。
操作:
insert x y:将yy加入链表,插入在第一个值为xx的结点之前。若链表中不存在值为xx的结点,则插入在链表末尾。保证xx,yy为int型整数。
delete x:删除链表中第一个值为xx的结点。若不存在值为xx的结点,则不删除。

输入描述:

第一行输入一个整数n (1≤n≤10^4),表示操作次数。
接下来的n行,每行一个字符串,表示一个操作。保证操作是题目描述中的一种。

输出描述:

输出一行,将链表中所有结点的值按顺序输出。若链表为空,输出"NULL"(不含引号)。

代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* next;
} node;

struct node* init() {
    struct node* n = (struct node*)malloc(sizeof(struct node));
    n->next = NULL;
    n->data = -1;
    return n;
}

void insert(struct node* l, int beforeme, int data) {
    struct node* n = (struct node*)malloc(sizeof(struct node));
    n->data = data;
    struct node* tmp = l;
    while (1) {
        if (tmp->next == NULL) {
            tmp->next = n;
            n->next = NULL;
            break;
        } else {
            if (tmp->next->data == beforeme) {
                n->next = tmp->next;
                tmp->next = n;
                break;
            }
            tmp = tmp->next;
        }
    }
}

void delete (struct node* l, int target) {
    struct node* tmp = l;
    while (1) {
        if (tmp->next == NULL) {
            if (tmp->data == target) {
                free(tmp);
            } else {
                break;
            }
        } else if (tmp->next->data == target) {
            struct node* tmpp = tmp->next;
            tmp->next = tmp->next->next;
            free(tmpp);
            break;
        } else {
            tmp = tmp->next;
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    struct node* l = init();
    for (int i = 0; i < n; i ++) {
        char op[7];
        scanf("%s", op);
        if (strcmp(op, "insert") == 0) {
            int afterme, data;
            scanf("%d %d", &afterme, &data);
            insert(l, afterme, data);
        } else if (strcmp(op, "delete") == 0) {
            int target;
            scanf("%d", &target);
            delete (l, target);
        }
    }
    struct node* tmp = l->next;
    if (tmp == NULL) {
        printf("NULL\n");
    } else {
        while (tmp != NULL) {
            printf("%d ", tmp->data);
            tmp = tmp->next;
        }
    }
    return 0;
}

问题

关于调用free函数释放内存的问题,之前是delete函数里是这样释放的

		else if (tmp->next->data == target) {
            tmp->next = tmp->next->next;
            free(tmp->next);
            break;
        }

然而此时tmp的next已经更新了,所以需要创建一个指针指向tmp的next,最后释放该指针指向的空间:

		else if (tmp->next->data == target) {
            struct node* tmpp = tmp->next;
            tmp->next = tmp->next->next;
            free(tmpp);
            break;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值