代码随想录算法训练营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;
}
};