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 dummy=ListNode(-1);
ListNode *cur=&dummy;
dummy.next=head;
while(cur->next){
if(cur->next->val==val){
cur->next=cur->next->next;
}
else
cur=cur->next;
}
return dummy.next;
}
};
使用虚拟头节点,避免删除元素在头部时处理逻辑不一致的问题。
class MyLinkedList {
public:
MyLinkedList() {
size_=0;
head_=new ListNode(-1);
}
int get(int index) {
if(index<0||index>=size_)
return -1;
auto cur=head_;
for(int i=0;i<index+1;i++){
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
auto node=new ListNode(val);
node->next=head_->next;
head_->next=node;
size_++;
}
void addAtTail(int val) {
auto node=new ListNode(val);
auto cur=head_;
while(cur->next){
cur=cur->next;
}
cur->next=node;
size_++;
}
void addAtIndex(int index, int val) {
if(index<0||index>size_)
return;
auto node=new ListNode(val);
auto cur=head_;
for(int i=0;i<index;i++){
cur=cur->next;
}
node->next=cur->next;
cur->next=node;
size_++;
}
void deleteAtIndex(int index) {
if(index<0||index>=size_)
return;
auto cur=head_;
for(int i=0;i<index;i++){
cur=cur->next;
}
cur->next=cur->next->next;
size_--;
return;
}
private:
int size_;
ListNode *head_;
};
/**
* 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);
*/
引入虚拟头,所以处于index的节点,需要从头结点出发,步进index+1次才能到达,插入/删除时,需要找到它的【前置节点】进行指针操作。
206.反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre=nullptr, *cur=head;
while(cur){
auto temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
双指针思想。
348

被折叠的 条评论
为什么被折叠?



