力扣203.移除链表元素
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
思路:遍历链表时,不能直接移动头节点,因为链表最后要返回头结点。所以需要创建一个临时指针指向头结点。两种方法。第一种:直接使用原来的链表,这种方法分为两个部分,第一部分移除头结点,头结点向后移动一位即可,由于C++内存释放规则,需要创建一个temp指针指向原先需要删除的头节点。第二部分移除其他节点。第二种,创建虚拟头结点,在头结点前创建一个虚拟节点指向头结点,这样移除方式就变成统一的了。
C++代码:
lass Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//原链表
//删除头结点
// while (head!=NULL && head->val==val){
// ListNode* temp=head;
// head=head->next;
// delete temp;
// }
//删除其他结点
// ListNode* cur=head;
// while(cur!=NULL&&cur->next!=NULL){
// if(cur->next->val==val){
// ListNode*temp=cur->next;
// cur->next=cur->next->next;
// delete temp;
// }
// else{
// cur=cur->next;
// }
// }
// return head;
//虚拟头结点
ListNode* dummyHead=new ListNode(0);
dummyHead->next=head;
ListNode* cur=dummyHead;
while(cur->next!=NULL){
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.设计链表
题目链接:707. 设计链表 - 力扣(LeetCode)
思路:
C++代码:
lass MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
MyLinkedList() {
_dummyHead=new LinkedNode(0);
_size=0;
}
int get(int index) {
if(index<0 || index>(_size-1)){
return -1;
}
LinkedNode* cur=_dummyHead->next;
while(index--){
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
//先让新节点的next指向dummy的next
LinkedNode* newNode=new LinkedNode(val);
newNode->next=_dummyHead->next;
_dummyHead->next=newNode;
_size++;
}
void addAtTail(int val) {
LinkedNode* newNode=new LinkedNode(val);
LinkedNode* cur=_dummyHead;
while(cur->next!=nullptr){
cur=cur->next;
}
cur->next=newNode;
_size++;
}
void addAtIndex(int index, int val) {
if(index>_size)return;
if(index<0)index=0;
LinkedNode* newNode=new LinkedNode(val);
LinkedNode* cur=_dummyHead;
while(index--){
cur=cur->next;
}
newNode->next=cur->next;
cur->next=newNode;
_size++;
}
void deleteAtIndex(int index) {
if(index>=_size || index<0) {
return;
}
LinkedNode* cur=_dummyHead;
while(index--){
cur=cur->next;
}
LinkedNode* temp=cur->next;
cur->next=cur->next->next;
delete temp;
temp=nullptr;
_size--;
}
private:
int _size;
LinkedNode* _dummyHead;
};
力扣206.反转链表
题目链接:206. 反转链表 - 力扣(LeetCode)
思路:双指针写法 递归写法
C++代码:
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur==nullptr)return pre;
ListNode* temp=cur->next;
cur->next=pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
//双指针法
// ListNode* pre=nullptr;
// ListNode* cur=head;
// ListNode* temp;
// while(cur){
// temp=cur->next;
// cur->next=pre;
// pre=cur;
// cur=temp;
// }
// return pre;
return reverse(nullptr,head);
}
};