代码随想录算法训练营day3

代码随想录算法训练营day3| 203. 移除链表,707.设计链表 

203.移除链表 leetcode203 Remove Linked List Elements

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
     ListNode*dummyhead=new ListNode(0);//设置新的虚拟头结点
     dummyhead->next=head;//将虚拟头结点接到头上
     ListNode*cur=dummyhead; //cur就是现在要开始遍历的元素
     while(cur->next!=NULL){ //判断这个链表不为空,开始循环
         if(cur->next->val==val)//查找链表中是否等于val
         {
             ListNode*tmp=cur->next;//为了删除,所以增加临时tmp
             cur->next=cur->next->next;//使这个直接变成下一个
            delete tmp;//删除这个临时结点
         }
         else{
             cur=cur->next;//没有的话就直接去下一个
         }
     }
     head=dummyhead->next; //头现在是虚拟头结点,所以要把头搞回来
     delete dummyhead;//C++还得自己删除虚拟结点,丑陋
     return head; //根据题意返回头结点
    }
};


 

707.设计链表 leetcode 707 design linked list

class MyLinkedList {
public://公有成员
struct LinkedNode{
int val;
LinkedNode*next;
LinkedNode(int val):val(val),next(nullptr){}//定义链表节点结构体
};
//初始化链表,构造虚拟头,赋值链表
MyLinkedList() {
dummyhead=new LinkedNode(0);
size=0;
}
//获取到第index个节点数值,如果index是非法数值直接返回-1,index从0开始
int get(int index) {
if(index>_size||index<0)
{return -1;}
while(index--)
{
cur=cur->next;
}
return cur->val;
}
//在链表中插入一个节点
void addAtHead(int val) {
LinkedNode*newNode=new LinkedNode(0);
newNode->next=dummyhead->next;
dummyhead->next=newNode;
_size++;
}
void addAtTail(int val){
LinkedNode*newNode=new LinkedNode(0);
LinkedNode*cur=dummyhead;
while(cur->next!=nullptr)
{
cur=cur->next;
}
cur->next=newNode;
_size++;
}
void addAtIndex(int index,int val){
if(index>_size||index<0) {
return;
}
LinkedNode*newNode=new LinkedNode(val);
LinkedNode*cur=dummyhead;
while(index--){
cur=cur->next;
}
newNode->next=cur->next;
cur->next=newNode;
_size++;}
void deleteAtIndex(int index){
if(index>=_size||index<0){
return;
}
LinkedNode*cur=dummyhead;
while(index--)
{
cur=cur->next;
}
LinkedNode*tmp=cur->next;
cur->next=cur->next->next;
delete tmp;
_size--;
private://私有成员
int _size;
LinkedNode*dummyhead;

}

};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值