203.移除链表元素
直接说想法吧,首先是在头节点之前加入一个虚拟头节点dummyhead,让虚拟节点指向头节点,这样在删除头节点head和其他节点时的操作就统一起来了,需要注意的是不能对空指针进行操作,因为要对cur->next的值或者下一个位置进行处理,所以在while循环时要判断一下cur->next是否为空指针。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead= new ListNode();
dummyhead->next=head;
ListNode* cur=dummyhead;
while(cur->next!=NULL)
{
if(cur->next->val==val)
{
ListNode* tmp=cur->next;
cur->next=cur->next->next;
delete tmp;
}
else
{
cur=cur->next;
}
}
head=dummyhead->next;
delete dummyhead;
return head;
}
};//使用虚拟头节点
下面的代码是直接对原链表进行操作,需要分情况讨论,头节点和非头节点,并且要注意释放内存。同时在while循环的判断条件里,不能对空指针进行操作。
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;
}
};//直接对原链表进行操作
总结一下,对链表的语法还不太熟悉,继续学习。
707.设计链表
class 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)
{
return -1;
}
LinkedNode* cur=_dummyhead->next;
while(index--)
{
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
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!=NULL)
{
cur=cur->next;
}
cur->next=newNode;
_size++;
}
void addAtIndex(int index, int val) {
if(index>_size)
{
return;
}
else
{
LinkedNode* cur=_dummyhead;
while(index--)
{
cur=cur->next;
}
LinkedNode* newNode=new LinkedNode(val);
newNode->next=cur->next;
cur->next=newNode;
_size++;
}
}
void deleteAtIndex(int index) {
if(index<0 || index>=_size)
{
return;
}
LinkedNode* cur=_dummyhead;
while(index--)
{
cur=cur->next;
}
LinkedNode* tmp=cur->next;
cur->next=cur->next->next;
delete tmp;
_size--;
}
private:
int _size;
LinkedNode* _dummyhead;
};
总结:注意index是从0开始的,第0个节点就是头结点
206.反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* dummyhead=new ListNode();
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur!=NULL)
{
ListNode* tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};//双指针法
总结:自己卡住的地方:cur和pre不知道如何移动