链表结构
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) {}
};
203.移除链表元素
法一:
头节点与非头节点分开处理
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 删除头结点
while (head != NULL && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// 删除非头结点
ListNode* cur = head;
while (cur != NULL && cur->next!= NULL) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};
法二:
添加伪头节点
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(); // 设置一个虚拟头结点
dummyHead->next=head;
ListNode* p=dummyHead;
while(p->next){
if(p->next->val==val){
ListNode *tmp=p->next;
p->next=p->next->next;
delete tmp;
}else{
p=p->next;
}
}
head=dummyHead->next;
delete dummyHead;
return head;
}
};
class MyLinkedList {
public:
MyLinkedList() {
this->size=0;
this->head=new ListNode(0);
}
int get(int index) {
if(index<0||index>=size)
return -1;
ListNode *p=head->next;
while(index--){
p=p->next;
}
return p->val;
}
void addAtHead(int val) {
addAtIndex(0,val);
}
void addAtTail(int val) {
addAtIndex(size,val);
}
void addAtIndex(int index, int val) {
if(index>size)
return;
if(index<0)
index=0;
ListNode* p=head;
while(index--){
p=p->next;
}
ListNode* newNode = new ListNode(val);
newNode->next=p->next;
p->next=newNode;
size++;
}
void deleteAtIndex(int index) {
if(index<0||index>=size)
return;
ListNode* p=head;
while(index--){
p=p->next;
}
ListNode* tmp=p->next;
if(tmp)
p->next=tmp->next;
delete tmp;
size--;
}
private:
int size;
ListNode *head; //伪头节点
};
206.反转链表
法一:
迭代 双指针
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p=head,*pre=NULL; //要先把第一个节点指向NULL
while(p){
ListNode *t=p->next;
p->next=pre;
pre=p;
p=t;
}
return pre;
}
};
法二:
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* newHead=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return newHead;
}
};
第二种递归
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur == NULL) return pre;
ListNode* temp = cur->next;
cur->next = pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
return reverse(NULL, head);
}
};
法三:
添加头节点 利用头插法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* dummyHead=new ListNode(0);
dummyHead->next=NULL;
ListNode* p=head;
while(p){
ListNode* t=p->next;
p->next=dummyHead->next;
dummyHead->next=p;
p=t;
}
return dummyHead->next;
}
};