北林oj236——删除链表中绝对值相等的结点

  • 题目描述

  • 解题思路心得

是某年408真题,思路就是空间换时间,辅助数组记录绝对值出现与否,若该绝对值出现过就删掉。

实现的时候输入时偷偷记录了链表绝对值最大值,然后创建长度为最大值的辅助数组。

  • 代码

#include <iostream>
#include <stdlib.h>
using namespace std;
struct LNode
{
    int data;
    LNode *next;
};
int creatlist(LNode *&L, int length)
{
    LNode *p = L;
    int max = 0;
    for (int i = 0; i < length; i++)
    {
        LNode *tmp = new LNode;
        cin >> tmp->data;
        tmp->next = NULL;
        if (abs(tmp->data) > max)
            max = tmp->data;
        p->next = tmp;
        p = p->next;
    }
    return max;
}
int printlist(LNode *L)
{
    LNode *p = L->next;
    int count = 0;
    if (p == NULL)
    {
        return 0;
    }
    while (p)
    {
        cout << p->data;
        if (p->next != NULL)
        {
            cout << " ";
        }
        p = p->next;
        count++;
    }
    cout << endl;
    return count;
}
void funlist(LNode *&L, int max)
{
    int *array = new int[max];
    LNode *p=L->next;
    LNode *r=L;
    for (int i = 0; i < max; i++)
    {
        array[i]=0;
    }
    while (p)
    {
        if (array[abs(p->data)]==0)
        {
            array[abs(p->data)]=1;
            p=p->next;
            r=r->next;
        }else{
            r->next=p->next;
            free(p);
            p=r->next;
        }    
    }
    delete[]array;
}
int main()
{
    int n = 0;
    int max = 0;
    while (1)
    {
        LNode *L = new LNode;
        L->next = NULL;
        cin >> n;
        if (!n)
        {
            break;
        }
        max=creatlist(L, n);
        funlist(L,max+1);
        printlist(L);
    }
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值