203. 移除链表元素
cpp
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* Head = new ListNode();
Head->next = head;
ListNode* out1 = Head;
while(Head!=nullptr && Head->next!=nullptr){
if(Head->next->val == val){
ListNode* tmp = Head->next->next;
delete Head->next;
Head->next = tmp;
}else{
Head = Head->next;
}
}
ListNode* out2 = out1->next;
delete out1;
return out2;
}
};
707. 设计链表
cpp
struct ln{
int val;
ln* next;
ln():val(0), next(nullptr){}
ln(int val):val(val), next(nullptr){}
ln(int val, ln* next):val(val), next(next){}
};
class MyLinkedList {
public:
ln *head = nullptr;
ln *tail = nullptr;
int num = 0;
MyLinkedList() {
head = new ln();
tail = head;
}
ln* find(int index){
ln* ob = head;
for(int i=0; i<index; ++i){
if(ob!=nullptr){
ob = ob->next;
}else{
return nullptr;
}
}
return ob;
}
int get(int index) {
ln* ob = find(index);
if(ob==nullptr){return -1;}
ob = ob->next;
return ob==nullptr? -1: ob->val;
}
void addAtHead(int val) {
ln* n = head->next;
head->next = new ln(val, n);
num++;
}
void addAtTail(int val) {
ln* n = find(num);
n->next = new ln(val);
num++;
}
void addAtIndex(int index, int val) {
ln* ob = find(index);
if(ob==nullptr){return;}
ln* tmp = ob->next;
ob->next = new ln(val, tmp);
num++;
}
void deleteAtIndex(int index) {
ln* ob = find(index);
if(ob==nullptr){return;}
ln* tmp = ob->next;
if(tmp==nullptr){return;}
tmp = tmp->next;
delete ob->next;
ob->next = tmp;
num--;
}
};
206. 反转链表
cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr){return nullptr;}
ListNode* tmp = nullptr;
ListNode* out = nullptr;
while(head!=nullptr){
tmp = head->next;
head->next = out;
out = head;
head = tmp;
}
return out;
}
};