List(double linked)

简易版链表 ,目前还有些问题,
1.由于构造函数中会new一个Node,所以链表中会多出一个由默认T()构造的Node
2.打印链表中的元素非常不方便

/*
LIST-SEARCH(L,k)
x=L.head
while x!=NIL and key !=k
    x=x.next
return x

LIST-INSERT(L,x)
x.next= L.head
if L.head!=NIL
    L.head.prev=x
L.head=x
x.prev=NIL

LIST-DELETE(L,x)
if x.prev!=NIL
    x.prev.next=x.next
else L.head=x.next
if x.next!=NIL
    x.next.prev=x.prev
*/

h

#pragma once
template<class T>
struct Node {
    T data;
    Node* prev;
    Node* next;
};

template<class T>
class List {
private:
    Node<T>* head;
public:
    List();
    ~List();

    Node<T>* ListSearch(const T& k) const;
    bool ListInsert(const T rhs);
    bool ListDelete(T x);


};

cpp

#include"List.h"
#include<iostream>
template<class T>
List<T>::List() :head(new Node<T>) {
    head->prev = nullptr;
    head->next = nullptr;
    head->data = T();
}
template<class T>
List<T>::~List() {
    while (head != nullptr) {
        auto de = head;
        head = head->next;
        delete de;
    }
}


template<class T>
Node<T>*  List<T>::ListSearch(const T& k) const {
    auto current = head;
    while (current != nullptr && current->data != k) {
        current = current->next;
    }
    return current;
}

template<class T>
bool  List<T>::ListInsert(const T rhs) {
    auto temp = new Node<T>;
    temp->data = rhs;
    head->prev = temp;
    temp->next = head;
    temp->prev = nullptr;
    head = temp;
    return true;
}

template<class T>
bool  List<T>::ListDelete(T x) {
    auto de = ListSearch(x);
    if (de != nullptr) {
        if (de->prev == nullptr&&de->next == nullptr) {
            delete de;
        }else if (de->prev == nullptr) {
            head = de->next;
            head->prev = nullptr;
            de->next = nullptr;
            delete de;
        }else if (de->next == nullptr){
            de->prev->next = nullptr;
            de->prev = nullptr;
            delete de;
        }
        else {
            de->prev->next = de->next;
            de->next->prev = de->prev;
            de->prev = nullptr;
            de->next = nullptr;
            delete de;
        }
        return true;
    }
    return false;
}

text:

int main() {

    List<int> Li;

    Li.ListInsert(1);
    Li.ListInsert(2);
    Li.ListInsert(3);
    Li.ListInsert(4);
    Li.ListInsert(5);
    std::cout << Li.ListSearch(1)->data << std::endl;
    std::cout << Li.ListSearch(2)->data << std::endl;
    std::cout << Li.ListSearch(3)->data << std::endl;
    std::cout << Li.ListSearch(4)->data << std::endl;
    std::cout << Li.ListSearch(5)->data << std::endl;

    Li.ListDelete(3);

    Li.ListDelete(5);

    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值