链表基础知识
- 建议先自定义创建结点的函数,这样可以直接赋值,直接调用C++的函数需要再进行一步赋值
- 用虚拟头结点来统一链表的增加删除结点操作(因为增加和删除会涉及到是否是第一个结点)
- 在返回头指针的时候返回的是dummyhead->next,之前的head指向的结点可能早已经不是第一个
- 实现MyLinkedList类,类变量只能定义一次
- 翻转链表不用增加结点,不用定义虚拟头结点
203 删除链表指定数值的元素
下文中temp指针起到了一个过渡阶段,如果直接cur->next=cur->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* temp=cur->next;
cur->next=temp->next;
delete temp;
}
else{
cur=cur->next;
}
}
head=dummynode->next;
delete dummynode;
return head;
}
};
707设计链表
对于类的创建不熟悉,类变量只能定义一次,由于重复定义而报错。
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode *next;
ListNode(int val) : val(val), next(nullptr) {}
};
MyLinkedList() {
ListNode* dummyhead=new ListNode(0);//dummyhead=new ListNode(0);
size=0;
}
int get(int index) {
if(index<size && index>=0){
ListNode* cur=dummyhead->next;
while(index--){
cur=cur->next;
}
return cur->val;
}
else
return -1;
}
void addAtHead(int val) {
ListNode* newnode=new ListNode(val);
newnode->next=dummyhead->next;
dummyhead->next=newnode;
size++;
}
void addAtTail(int val) {
//ListNode* cur=dummyhead->next;如果是空链表
ListNode* cur=dummyhead;
ListNode* newnode=new ListNode(val);
while(cur->next != nullptr)
cur=cur->next;
cur->next=newnode;
size++;
}
void addAtIndex(int index, int val) {
if(index>size) return;
else if(index<0) index=0;
else {
ListNode* cur=dummyhead;
ListNode* newnode=new ListNode(val);
while(index--){
cur=cur->next;
}
newnode->next=cur->next;
cur->next=newnode;
size++;
}
}
void deleteAtIndex(int index) {
if(index<0 || index>size) return;
ListNode* cur=dummyhead;
while(index--){
cur=cur->next;
}
ListNode* temp=cur->next;
cur->next=cur->next->next;
delete temp;
}
}
private:
int size;
ListNode* 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反转链表
自己的代码:理不清双指针该如何赋初始值,while循环的判断条件也总分析不对
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur=head;
ListNode* temp;
ListNode* pre=nullptr;
if(head==nullptr) return nullptr;
while(cur->next!=nullptr){//cur
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
第二种写法:递归,不断地自己调用自己,其实就是双指针的改写