移除链表元素
题目解答
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* Head = new ListNode(0);
Head->next = head;
ListNode* cur = Head;
while (cur->next != nullptr) {
if (cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else cur = cur->next;
}
head = Head->next;
delete Head;
return head;
}
};
解题心得
1、链表的题目一定要画图。
2、设置虚拟头结点能够更好地解答,使代码风格统一。
设计链表
题目解答
class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val) :val(val), next(nullptr) {}
};
MyLinkedList() {
_size = 0;
_dummyHead = new LinkedNode(0);
}
int get(int index) {
if (index > _size-1) return -1;
LinkedNode* point = _dummyHead;
for (int i = 0; i <= index; i++) point = point->next;
return point->val;
}
void addAtHead(int val) {
LinkedNode* node = new LinkedNode(val);
node->next = _dummyHead->next;
_dummyHead->next = node;
_size++;
}
void addAtTail(int val) {
LinkedNode* cur = _dummyHead;
while (cur->next != nullptr) cur = cur->next;
LinkedNode* node = new LinkedNode(val);
cur->next = node;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) return;
LinkedNode* point = _dummyHead;
for (int i = 0; i < index; i++) point = point->next;
LinkedNode* cur = new LinkedNode(val);
cur->next = point->next;
point->next = cur;
_size++;
}
void deleteAtIndex(int index) {
if (index > _size - 1)return;
LinkedNode* point = _dummyHead;
for (int i = 0; i < index; i++) point = point->next;
LinkedNode* cur = point->next;
point->next = cur->next;
delete cur;
_size--;
}
private:
int _size;
LinkedNode* _dummyHead;
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/
解题心得
1、要运用虚拟头结点来解题,这样会更方便。
2、每次对链表进行增添元素或删除元素时,都要对_size做加加或者做减减的操作。
3、对链表的一个节点操作,要拿到该节点的前一个节点和后一个节点。
反转链表
题目解答
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr) return NULL;
ListNode* cur=head;
ListNode* pro=NULL;
while(cur){
ListNode* temp=cur;
cur=cur->next;
temp->next=pro;
pro=temp;
}
delete cur;
return pro;
}
};
解题心得
使用双指针解题,就能改变next的指向,从而使链表反转。