今天的学习加深了对链表的运用以及理解。
问题1:203.移除链表元素
思路:首先明确单向链表的构成,移除一个元素应直接将前一个指针指向后一个位置即可,同时要释放删除元素的位置,代码如下:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
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;
}
};
问题2:707.设计链表
该题对链表的基本操作要求很强,不过在明确了链表的结构之后,添加,删除,查询操作都还挺好些,代码如下:
class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
MyLinkedList() {
_dummmyhead=new LinkedNode(0);
_size=0;
}
int get(int index) {
if(index<0 || index>_size-1) return -1;
LinkedNode* cur=_dummmyhead->next;
while(index--){
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedNode* node=new LinkedNode(val);
node->next=_dummmyhead->next;
_dummmyhead->next=node;
_size++;
}
void addAtTail(int val) {
LinkedNode* node=new LinkedNode(val);
LinkedNode* cur=_dummmyhead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next=node;
_size++;
}
void addAtIndex(int index, int val) {
if(index > _size) return;
if(index < 0) index = 0;
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummmyhead;
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 = _dummmyhead;
while(index--) {
cur = cur ->next;
}
LinkedNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp=nullptr;
_size--;
}
private:
int _size;
LinkedNode* _dummmyhead;
};
问题3:反转链表
思路:双指针法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur=head;
ListNode* pre=NULL;
ListNode* tmp;
while(cur){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};