c++链表

贴两个关于c++链表的代码

代码一是一个双向链表

#include <iostream>

using namespace std;

typedef struct PNODE {
    int m;
    struct PNODE *next;
    struct PNODE *previous;
} node, *Pnode;

int main()
{
    int n;
    cin >> n;
    Pnode PHead = new(node);
    Pnode PLast = new(node);
    PHead->next = PLast;
    PHead->previous = NULL;
    PLast->next = NULL;
    PLast->previous = PHead;
    Pnode PTail = PHead;
    for (int i = 0; i < n; i++) {
        Pnode PNew = new(node);
        cin >> PNew->m;
        PNew->previous = PTail;
        PNew->next = PTail->next;
        PTail->next = PNew;
        PNew->next->previous = PNew;
        PTail = PTail->next;
    }

    PTail = PLast->previous;
    while (PTail->previous != NULL) {
        cout << PTail->m << endl;
        PTail = PTail->previous;
    }

    return 0;
}

代码二是顺序表元素的比较和删除,题目如下

已知a、b和c三个递增有序的线性表,现在要求对a做如下操作:删除其中既即在b中出现又在c中出现的元素(注意同一表中的元素有可能重复)。

#include <iostream>

using namespace std;

typedef struct PNODE {
    int m;
    struct PNODE *next;
}PNode, *Node;

//这一块函数在写的时候调了好几次,个人认为可以加深对指针的理解
void Input(Node *P, int n)
{
    *P = new(PNode);
    Node PHead = *P;
    PHead->next = NULL;
    Node PTail = PHead;
    for (int i = 0; i < n; i++) {
        Node PNew = new(PNode);
        cin >> PNew->m;
        PNew->next = NULL;
        PTail->next = PNew;
        PTail = PNew;
    }
}

int main()
{
    int n, m, l;
    cin >> n >> m >> l;

    Node PNHead, PMHead, PLHead;
    Input(&PNHead, n);
    Input(&PMHead, m);
    Input(&PLHead, l);

    Node PNTail = PNHead;
    Node PMTail = PMHead;
    Node PLTail = PLHead;
    while (PNTail->next != NULL) {
      //这个地方&&前后不能颠倒,因为根据c++(c)语言编译器的特性从左向右判断,颠倒后就会报错
        while (PMTail->next != NULL && PNTail->next->m > PMTail->next->m)
            PMTail = PMTail->next;
        while (PLTail->next != NULL && PNTail->next->m > PLTail->next->m)
            PLTail = PLTail->next;
        if (PMTail->next == NULL || PLTail->next == NULL)
            break;
        if (PNTail->next->m == PMTail->next->m && PNTail->next->m == PLTail->next->m) {
            Node P = PNTail->next;
            PNTail->next = P->next;
          //这个地方建议养成这个习惯,减少写大东西的时候不必要的内存泄露
            delete(P);
        }
        else
            PNTail = PNTail->next;
    }

    PNTail = PNHead->next;
    while (PNTail != NULL) {
        cout << PNTail->m << endl;
        PNTail = PNTail->next;
    }

    return 0;
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值