代码随想录刷题随记3-链表
今天写的这三道题都比较基础,加上博客耗时1.5h左右
203.移除链表元素
leetcode链接
比较基础没啥技巧就纯删节点
为了方便操作一般都先虚拟出来一个头结点,这样会比较方便避免各种讨论
解题代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode * newhead=new ListNode(0);
newhead->next=head;
if(head==nullptr){
return nullptr;
}
ListNode * cur=head;
ListNode * pre=newhead;
while(cur!=nullptr){
if(cur->val==val){
pre->next=cur->next;
cur->next=nullptr;
delete(cur);
cur=pre->next;
}
else{
cur=cur->next;
pre=pre->next;
}
}
return newhead->next;
}
};
707.设计链表
leetcode链接
虽然是中等难度的题目,但是涉及到的问题都是链表的基础操作,主要是熟悉链表增删改查。
使用虚拟头结点后会变得异常方便,注意要维护一个链表长度的变量。
解题代码:
class MyLinkedList {
public:
struct LinkNode{
int val;
LinkNode* next;
LinkNode(int val):val(val),next(nullptr){}
};
MyLinkedList() {
_virhead=new LinkNode(0);//定义虚拟头结点
_size=0;
}
int get(int index) {
if(index>=_size){
return -1;
}
LinkNode *cur =_virhead;
while(index>=0&&cur!=nullptr){
cur=cur->next;
index--;
}
if(cur!=nullptr)
return
cur->val;
else
return -1;
}
void addAtHead(int val) {
LinkNode * newnode=new LinkNode(val);
newnode->next= _virhead->next;
_virhead->next=newnode;
_size++;
}
void addAtTail(int val) {
int size=this->_size;
LinkNode * cur=this->_virhead;
while(size>0){
cur=cur->next;
size--;
}
cur->next=new LinkNode(val);
this->_size++;
}
void addAtIndex(int index, int val) {
if(index>this->_size){
return ;
}
if(index==this->_size){
addAtTail(val);
return;
}
LinkNode * cur=this->_virhead;
while(index>0){
cur=cur->next;
index--;
}
LinkNode * newnode=new LinkNode(val);
newnode->next=cur->next;
cur->next=newnode;
this->_size++;
}
void deleteAtIndex(int index) {
if(index>=this->_size){
return;
}
LinkNode * cur=this->_virhead;
while(index>0){
cur=cur->next;
index--;
}
LinkNode * tmp=cur->next;
cur->next=cur->next->next;
tmp->next=nullptr;
delete (tmp);
this->_size--;
}
LinkNode * _virhead;
int _size;
};
206.反转链表
leetcode链接
一道常见的基础链表题目。
程序代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr)
return nullptr;
ListNode * virhead=new ListNode(0);
virhead->next=head;
ListNode * cur=head;
ListNode *pre =nullptr;
ListNode * next;
while(cur!=nullptr){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};