AB9 模板【链表】

 1. 超时,测试点 6/10

#include<iostream>
using namespace std;

class Node {
  public:
    int data;
    Node* next;
};

class List {
  public:
    List() {
        head = NULL;
    }

    Node* InsertNodeByIndex(int index, int x);
    Node* InsertNodeByValue(int x, int y);
    void DeleteNode(int x);
    void DisplayList();
    Node* head;
  private:


};

Node* List::InsertNodeByIndex(int index, int x) {
    if (index < 0) return NULL;

    int curIndex = 1;
    Node* curNode = head;
    while (curNode && index > curIndex) {
        curNode = curNode -> next;
        curIndex++;
    }

    Node* newNode = new Node;
    newNode -> data = x;
    if (index == 0) {
        newNode -> next = head;
        head = newNode;
    } else {
        newNode -> next = curNode -> next;
        curNode -> next = newNode;
    }

    return newNode;
}

Node* List::InsertNodeByValue(int x, int y) {
    Node* preNode = NULL;
    Node* curNode = head;
    int curIndex = 1;

    while (curNode && curNode -> data != x) {
        preNode = curNode;
        curNode = curNode -> next;
        curIndex++;
    }
    Node* newNode = new Node;
    newNode -> data = y;

    //如果链表为空
    if (curIndex == 1) {
        newNode -> next = head;
        head = newNode;
    }
    //链表不为空
    else {
        //如果找到了curNode
        if (curNode) {
            preNode -> next = newNode;
            newNode -> next = curNode;
        }
        //没找到curNode
        else {
            preNode -> next = newNode;

        }
    }

    return newNode;
}

void List::DeleteNode(int x) {

    Node* preNode = NULL;
    Node* curNode = head;

    while (curNode && curNode -> data != x) {
        preNode = curNode;
        curNode = curNode -> next;
    }

    if (curNode) {
        if (preNode) {
            preNode -> next = curNode -> next;
            delete curNode;
        } else {
            head = curNode -> next;
            delete head;
        }
    }
}

void List::DisplayList() {
    Node* curNode = head;
    while (curNode != NULL) {
        cout << curNode -> data << ' ';
        curNode = curNode -> next;
    }
}

int main() {
    List list;
    int num;
    cin >> num;
    for (int i = 0; i < num; i++) {
        string s;
        cin >> s;
        if (s == "insert") {
            int x, y;
            cin >> x >> y;
            list.InsertNodeByValue(x, y);
        } else {
            int value;
            cin >> value;
            list.DeleteNode(value);
        }
    }
    if (list.head == NULL) {
        cout << "NULL";

    } else {
        list.DisplayList();
    }


    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值