203.移除链表元素
707.设计链表
难点在于对边界的判断,还有要保证判断的节点非空节点。
class MyLinkedList {
struct LinkedNode{
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
private:
int size;
LinkedNode* dummy;
public:
MyLinkedList() {
dummy = new LinkedNode(0);
size = 0;
}
int get(int index) {
if(index >= size) return -1;
auto* current = dummy;
while(index-- >= 0) {
current = current->next;
}
if(!current) return -1;
return current->val;
}
void addAtHead(int val) {
LinkedNode* newHead = new LinkedNode(val);
auto* head = dummy->next;
newHead->next = head;
dummy->next = newHead;
size++;
}
void addAtTail(int val) {
auto* current = dummy;
for(int i = 0; i < size; ++i) {
current = current->next;
}
auto* newTail = new LinkedNode(val);
current->next = newTail;
size++;
}
void addAtIndex(int index, int val) {
if(index == size) {
addAtTail(val);
return;
}else if(index > size)
{
return;
}else if(index == 0)
{
addAtHead(val);
return;
}
auto* newNode = new LinkedNode(val);
auto* current = dummy;
while(index--) {
current = current->next;
}
auto* pNode = current->next;
current->next = newNode;
newNode->next = pNode;
size++;
}
void deleteAtIndex(int index) {
if(index > size - 1) return;
auto* current = dummy;
while(index--) {
current = current->next;
}
if(!current) return;
auto* pNode = current->next;
if(!pNode) return;
auto* ppNode = pNode->next;
current->next = ppNode;
delete pNode;
size--;
}
};
/**
* 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);
*/
206.反转链表
题目思路本身很明确,难点在于头节点如何定义。按照往常的习惯虚节点定义为ListNode(0,head)在这里就不适用,最后打印会多出一个0。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return nullptr;
ListNode* dummy;
auto* left = dummy;
auto* right = head;
while(right) {
auto* temp = right->next;
right->next = left;
left = right;
right = temp;
}
return left;
}
};