移除链表元素
讲解:https://programmercarl.com/0203.%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1%A8%E5%85%83%E7%B4%A0.html
思路:使用虚拟的头节点dummyHead,这样可以避免判断是不是位于链表的头节点,从而可以统一操作。
// struct ListNode {
// int val;
// ListNode* next;
// ListNode(int x):val(x), next(nullptr) {}
// };
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead -> next = head;
ListNode* cur = dummyHead; //cur不用delete,因为不是创建在堆区。
int flag = 0;
while (cur -> next != nullptr) {
if (cur -> next -> val == val) {
ListNode* tmp = cur -> next;
cur -> next = cur -> next -> next;
delete tmp;
}
else {
cur = cur -> next;
}
cout << "flag:" << flag;
flag++;
}
head = dummyHead -> next;
delete dummyHead;
return head;
}
};
设计链表
讲解:
https://programmercarl.com/0707.%E8%AE%BE%E8%AE%A1%E9%93%BE%E8%A1%A8.html
class MyLinkedList {
public:
struct LinkNode {
int val;
LinkNode* next;
LinkNode(int x):val(x), next(nullptr) {}
};
MyLinkedList() {
_dummyhead = new LinkNode(0);
_size = 0;
}
int get(int index) {
// if (index < 0 || index > (_size - 1)) {
// return -1;
cout<<"get: "<<_size<<endl;
if (index < 0) return -1;
if (index > (_size - 1)) return -1;
// }
else {
LinkNode* cur = _dummyhead->next;
while (index--) {
cur = cur->next;
}
return cur->val;
}
}
void addAtHead(int val) {
LinkNode* newnode = new LinkNode(val);
newnode->next = _dummyhead->next;
_dummyhead->next = newnode;
_size++;
cout<<"addathead: "<< _size<<endl;
}
void addAtTail(int val) {
LinkNode* newnode = new LinkNode(val);
LinkNode* cur = _dummyhead;
while (cur->next != nullptr) {
cur = cur->next;
}
// newnode->next = cur->next;
cur->next = newnode;
_size++;
cout<<"addattail: "<<_size<<endl;
}
void addAtIndex(int index, int val) {
if (index < 0 || index > (_size)) {
return;
}
else {
LinkNode* newnode = new LinkNode(val);
LinkNode* cur = _dummyhead;
while (index--) {
cur = cur->next;
}
newnode->next = cur->next;
cur->next = newnode;
_size++;
}
cout<<"addatindex: "<<_size<<endl;
}
void deleteAtIndex(int index) {
if (index < 0 || index > (_size - 1)) {
return;
}
else {
LinkNode* cur = _dummyhead;
while (index--) {
cur = cur->next;
}
LinkNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
_size--;
}
cout<<"deleteatindex: "<<_size<<endl;
}
private:
int _size;
LinkNode* _dummyhead;
};
/**
* 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);
*/
反转链表
讲解:https://programmercarl.com/0206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.html
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};