删除单链表


#include <iostream>

#include<algorithm>
#include<vector>

using namespace std;

template<typename T>
struct Node
{
    T data;
    Node <T> *next;

};

template<typename T>
class LinkList
{
public:
    LinkList();
    // ~LinkList();

public:
    bool ListInsert(int i, const T &e);
    bool ListDelete(int i);

    // bool GetElem(int i, T& e);
    // int LocateElem(const T&e);
    // void DispList();
    // int ListLength();
    // bool Empty();
    // void ReverseList();

private:
    Node<T> *m_head;
    int m_length;


};

template <typename T>
LinkList<T>::LinkList()
{
    m_head = new Node<T>;
    m_head->next = nullptr;
    m_length = 0;
}


template <typename T>
bool LinkList<T>::ListDelete(int i)
{
    cout << "sssssssssss11111111111" << endl;

    if (m_length < 1)
    {
        cout << "test" << endl;
        return false;
    }
    /*
    if (i < 1 || m_length)
    {
        return false;
    }
    */
    cout << "sssssssssss" << endl;
    Node<T> * p_curr = m_head;

    for (int j = 0; j < (i - 1); ++j)
    {

        p_curr = p_curr->next;
    }
    Node<T> *p_willdel = p_curr->next;
    p_curr->next = p_willdel->next;
    m_length--;
    cout << "成功删除位置为:" << i << "元素为:" << p_willdel->data << endl;
    delete p_willdel;


    
    return true;
}

//在单链表插入元素
template<typename T>
bool LinkList<T>::ListInsert(int i, const T & e)
{
    if (i < 1 || i >(m_length + 1))
    {
        cout << "222" << endl;
        return false;
    }

    Node<T> *p_curr = m_head;
    for (int j = 0; j < (i - 1); ++j)
    {
        p_curr = p_curr->next;

    }

    Node<T>*node = new Node<T>;
    node->data = e;
    node->next = p_curr->next;

    p_curr->next = node;
    cout << "e = " << e << endl;

    m_length++;

    return true;
}

//不带头节点

/*
template<typename T>
bool LinkList<T>::ListInsert(int i, const T &e)
{
    if (i < 1 || i >(m_length + 1))
    {
        return false;
    }
    //如果插入第一个位置
    if (i == 1)
    {
        Node<T> *node = new Node<T>;
        node->data = e;
        node->next = m_head;
        m_head = node;

        cout << "e = " << e << endl;
        m_length++;
        return true;
    }

    Node<T> *p_curr = m_head;
    for (int j = 1; j < (i - 1); ++j)
    {
        p_curr = p_curr->next;

    }

    Node<T>*node = new Node<T>;
    node->data = e;
    node->next = p_curr->next;
    p_curr->next = node;
    m_length++;
    cout << "e = " << e << endl;
    return true;
}
*/
int main()
{

    cout << "test1111111111" << endl;

    LinkList <int> sLinkJob;

    sLinkJob.ListInsert(1, 12);
    sLinkJob.ListInsert(2, 24);

    sLinkJob.ListInsert(3, 98);
    sLinkJob.ListDelete(2);


    getchar();


    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值