设置虚拟头节点是为了删除头节点时更加方便
注:不清除指针也能过,但为了防止出错,还是清除的好
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy=new ListNode(0);
dummy->next=head;
ListNode *cur=dummy;
while(cur->next!=nullptr)
{
if(cur->next->val==val)
{
//ListNode *tmp=cur->next;
cur->next=cur->next->next;
//delete tmp;
}
else
cur=cur->next;
}
//head=dummy->next;
//delete dummy;
//return head;
return dummy->next;
}
};
初版:细节内容没有考究,只是能过,后面得再看看
class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
MyLinkedList() {
dummy=new ListNode(0);
size=0;
}
int get(int index) {
if(index<0||index>size-1)
return -1;
else
{
ListNode *cur=dummy->next;
while(index--)
{
cur=cur->next;
}
return cur->val;
}
}
void addAtHead(int val) {
ListNode *cur=dummy;
ListNode *tmp=new ListNode(val);
tmp->next=cur->next;
cur->next=tmp;
size++;
}
void addAtTail(int val) {
ListNode *cur=dummy;
ListNode *tmp=new ListNode(val);
while(cur->next!=nullptr)
cur=cur->next;
cur->next=tmp;
tmp->next=nullptr;
size++;
}
void addAtIndex(int index, int val) {
if(index<0||index>size)
return ;
ListNode *cur=dummy;
ListNode *tmp=new ListNode(val);
while(index--)
cur=cur->next;
tmp->next=cur->next;
cur->next=tmp;
size++;
}
void deleteAtIndex(int index) {
if(index<0||index>size-1)
return ;
ListNode *cur=dummy;
while(index--)
cur=cur->next;
cur->next=cur->next->next;
size--;
}
private:
int size;
ListNode *dummy;
};
三个指针转转转,注意顺序,保留好cur->next就行了
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur=head;
ListNode *tmp;
ListNode *pre=nullptr;
while(cur!=nullptr)
{
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};