LeetCode 230.移除链表元素
题目链接
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* myHead = new ListNode(0);
myHead->next = head;
ListNode* cur = myHead;
while(cur->next != nullptr) {
if(cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = temp->next;
delete temp;
} else {
cur = cur->next;
}
}
head = myHead->next;
delete myHead;
return head;
}
};
LeetCode 707.设计链表
题目链接
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode* next;
ListNode(int val):val(val), next(nullptr) {}
};
MyLinkedList() {
dHead = new ListNode(0);
listSize = 0;
}
int get(int index) {
if(index >= listSize || index < 0) {
return -1;
}
ListNode *cur = dHead->next;
while(index > 0) {
cur = cur->next;
index --;
}
return cur->val;
}
void addAtHead(int val) {
ListNode *node = new ListNode(val);
node->next = dHead->next;
dHead->next = node;
listSize ++;
}
void addAtTail(int val) {
ListNode *node = new ListNode(val);
ListNode *cur = dHead;
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = node;
listSize ++;
}
void addAtIndex(int index, int val) {
ListNode *node = new ListNode(val);
if(index == listSize) {
addAtTail(val);
} else if(index < listSize && index >= 0) {
ListNode *cur = dHead;
while(index > 0) {
cur = cur->next;
index --;
}
node->next = cur->next;
cur->next = node;
listSize ++;
} else {
delete node;
}
}
void deleteAtIndex(int index) {
if(index <= listSize - 1 && index >= 0) {
ListNode *cur = dHead;
while(index > 0) {
cur = cur->next;
index --;
}
ListNode *temp = cur->next;
cur->next = temp->next;
listSize --;
delete temp;
}
}
private:
int listSize;
ListNode *dHead;
};
LeetCode 206.反转链表
题目链接
头插法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr) {
return head;
}
ListNode* dHead = new ListNode(0);
dHead->next = nullptr;
while(head != nullptr) {
ListNode* cur = head;
head = head->next;
cur->next = dHead->next;
dHead->next = cur;
}
return dHead->next;
}
};
双指针法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp;
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur != nullptr) {
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};