203.移除元素链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyNode=new ListNode(0);
dummyNode->next=head;
ListNode* cur=dummyNode;
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=dummyNode->next;
delete dummyNode;
return head;
}
};
主要是通过上一个节点来处理下一个节点的问题,然后需要虚拟头节点,这个做完707再看就简单了很多,相信下次应该就没什么问题了
707.设计链表
class MyLinkedList {
public:
struct ListNode{
int val;
ListNode* next;
ListNode(int val):val(val),next(nullptr){}
};
MyLinkedList() {
dummyNode_=new ListNode(0);
size_=0;
}
int get(int index) {
if (index > (size_ - 1) || index < 0) {
return -1;
}
ListNode* curNode=dummyNode_;
while(index--)
{
curNode=curNode->next;
}
return curNode->next->val;
}
void addAtHead(int val) {
ListNode* newNode= new ListNode(val);
newNode->next=dummyNode_->next;
dummyNode_->next=newNode;
size_++;
}
void addAtTail(int val) {
ListNode* newNode=new ListNode(val);
ListNode* curNode=dummyNode_;
while(curNode->next!=nullptr)
{
curNode=curNode->next;
}
curNode->next=newNode;
size_++;
}
void addAtIndex(int index, int val) {
if(index>size_)
{
return;
}
ListNode* newNode=new ListNode(val);
ListNode* curNode=dummyNode_;
while(index--)
{
curNode=curNode->next;
}
newNode->next=curNode->next;
curNode->next=newNode;
size_++;
}
void deleteAtIndex(int index) {
if(index>=size_||index<0)
{
return;
}
ListNode* curNode=dummyNode_;
while(index--)
{
curNode=curNode->next;
}
ListNode* tmp=curNode->next;
curNode->next=curNode->next->next;
delete tmp;
size_--;
}
private:
int size_;
ListNode* dummyNode_;
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/
基本上都是先看一遍才能写出来,还是需要多做几遍,最重要的就是虚拟节点的思维要有
206.反转链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre=nullptr;
ListNode* cur=head;
ListNode* tmp;
while(cur)
{
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};
双指针法,这实在是太巧妙了,最后的pre刚好走到最后,变成头节点,直接返回就可以了
我本来也是想这样设计,但是还是没考虑好 tmp=cur->next; 这个东西怎么传递到cur,看了解答豁然开朗