203.移除链表元素
思路:采用虚拟头结点的方法,多余的节点用delete删除
/**
* 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* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur = dummyhead;
while(cur->next!= nullptr){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else{cur = cur->next;}
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};
707.设计链表
自己做的时候越绕越晕,看了文章之后敲了一边。
class MyLinkedList {
public:
struct LinkNode{
int val;
LinkNode* next;
LinkNode(int val):val(val),next(nullptr){}
};
MyLinkedList() {
dummyhead = new LinkNode(0);
size = 0;
}
int get(int index) {
if(index<0||index>size-1) return -1;
LinkNode* cur = dummyhead->next; //head 区分addAtIndex
while(index){ //循环结束cur会停在index节点处 区分addAtIndex停在index-1处
cur = cur->next;
index--;
}
return cur->val;
}
void addAtHead(int val) {
LinkNode* tmp = new LinkNode(val);
tmp->next = dummyhead->next;
dummyhead->next = tmp;
size++;
}
void addAtTail(int val) {
LinkNode* tmp = new LinkNode(val);
LinkNode* cur = dummyhead;
while(cur->next!=NULL){
cur = cur->next;
}
tmp->next = cur->next;
cur->next = tmp;
size++;
}
// 在index前面插入 所以cur要停在index前面一个节点
void addAtIndex(int index, int val) {
if (index > size || index < 0) {
return;
}
LinkNode* tmp = new LinkNode(val);
LinkNode* cur = dummyhead; //循环结束会停在index前面一个节点
while(index){
cur = cur->next;
index--;
}
tmp->next = cur->next;
cur->next = tmp;
size++;
}
void deleteAtIndex(int index) {
if (index >= size || index < 0) {
return;
}
LinkNode* cur = dummyhead; //循环结束会停在index前面一个节点
while(index){
cur = cur->next;
index--;
}
LinkNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
size--;
}
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);
*/
206.反转链表
没想出来,一开始想着改变指针指向,发现只改变了后面的,不知道怎么去更新当前节点。看文章之后发现加一个pre前置指针就可以解决问题。
/**
* 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* next ;
ListNode * cur = head;
ListNode * pre = NULL;
while(cur!=NULL){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head = pre;
return head;
}
};