C++ 单向链表的创建、删除与显示

78 篇文章 1 订阅

代码如下所示:

#include <iostream>  
using namespace std;  
  
struct ListNode{
	int m_nValue;
	ListNode *m_pNext;
};

class List{
public:
	List(){
		pHead = nullptr;
	}
	void showList();//打印链表   
	void AddToTail(int value);//尾部添加节点   
	void RemoveNode(int value); //删除节点 
private:
	ListNode *pHead;
};
  
  
int main()  
{  
      
    List MyList;
	MyList.AddToTail(10);
    MyList.AddToTail(5);
	MyList.AddToTail(7);
	MyList.AddToTail(13);
	MyList.AddToTail(22);
	MyList.AddToTail(17); 
	
    MyList.showList();  
      
    MyList.RemoveNode(5); 
    MyList.showList();
     
    MyList.RemoveNode(13); 
    MyList.showList();
     
    MyList.RemoveNode(17); 
    MyList.showList(); 
     
    
 
      
    return 0;  
}  
  
  
  
void List::showList(){  
	ListNode *cur = pHead;
    while(cur != nullptr){  
        cout<<cur->m_nValue<<" ";  
        cur = cur->m_pNext;  
    }  
    cout<<endl;
}  
  
void List::RemoveNode(int value){  
    if(pHead == nullptr)  
        return;  
      
    ListNode *pre = pHead;  
    if(pHead->m_nValue == value){  
        pHead = pHead->m_pNext;  
        delete pre;  
        pre = nullptr;  
        return;  
    }  
    else{  
        ListNode *next = pre->m_pNext;     
        while(next != nullptr){  
            if(next->m_nValue == value){  
                pre->m_pNext = next->m_pNext;  
                delete next;  
                next = nullptr;  
                return;  
            }  
            pre = next;  
            next = next->m_pNext;      
        }     
    }         
}  
  
void List::AddToTail(int value){  

    ListNode *pNew = new ListNode;  
    pNew->m_nValue = value;  
    pNew->m_pNext = nullptr;  
      
    if(pHead == nullptr){  
        pHead = pNew;  
        return;  
    }         

    ListNode *node = pHead;  
    while(node->m_pNext != nullptr){  
        node = node->m_pNext;  
    }  
    
    node->m_pNext = pNew;  
    
} 

运行结果如下:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值