day 3:链表
首先是链表的定义要会自己写:
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
203:移除链表元素
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//定义虚拟头节点
ListNode* dummyhead = new ListNode(-1);
dummyhead->next = head;
//特判
if(head == nullptr) return nullptr;
ListNode* cur = dummyhead;
while(cur->next != nullptr){
if(cur->next->val == val){
cur->next = cur->next->next;
//等于的时候不跳,不等时候才跳
}else{
cur = cur->next;
}
}
return dummyhead->next;
}
};
707:老问题:设计链表:
class MyLinkedList {
public:
//定义结构体:
struct LinkedList{
int val;
LinkedList *next;
LinkedList( int val): val(val),next(nullptr){}
};
MyLinkedList() {
_dummyhead = new LinkedList(0);
_size = 0;
}
int get(int index) {
if(index > (_size -1 ) || index <0){
return -1;
}
LinkedList* cur = _dummyhead->next;
while(index--){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedList* newNode = new LinkedList(val);
newNode->next = _dummyhead->next;
_dummyhead->next = newNode;
_size++;
}
void addAtTail(int val) {
LinkedList* newNode = new LinkedList(val);
LinkedList* cur = _dummyhead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if(index > _size || index < 0 ){
return;
}
LinkedList* newNode = new LinkedList(val);
LinkedList* 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 ;
}
LinkedList* cur = _dummyhead;
while(index--){
cur = cur->next;
}
LinkedList* temp = cur->next;
cur->next = cur->next->next;
delete temp;
_size--;
}
//链表的两个属性
private:
int _size;
LinkedList *_dummyhead;
};
206:翻转链表:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur= head;
while(cur){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
/