203.移除链表元素
自我解释:就是移除一个链表中的一个元素,比较关键的点是如果是第一元素是不是需要另外判断一下,所以如果用一个比较统一的方式来做这一道题的话,就是加一个dummy head。
有几个地方第一次写的时候是错的, delete这个写错了,else忘记写了,
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
if(head == NULL)
{
return head;
}
// step 1. new a dummy head
ListNode* dummy_head = new ListNode(0);
// step 2. put the dummy head next point to the head
dummy_head->next = head;
// step 3. make the dummy head as current head
ListNode* curr_node = dummy_head;
while(curr_node->next != NULL){
if(curr_node->next->val == val)
{
//step 4. to delete
ListNode* temp = curr_node->next;
curr_node->next = curr_node->next->next;
delete temp;
}
else
{
//step 5. remember the in the else
curr_node = curr_node->next;
}
}
ListNode* res = dummy_head->next;
//step 6. delete the dummy head
delete dummy_head;
return res;
}
};
707.设计链表
这个是个基础题,但是有些边界如果没有注意的话也会出错
class MyLinkedList {
public:
struct LinkedNode
{
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr)
{}
};
MyLinkedList() {
dummy_head_ = new LinkedNode(0);
size_ = 0;
}
int get(int index) {
//1. 这个边界条件错了
if (index > size_-1 ||index <0)
{
return -1;
}
LinkedNode* cur = dummy_head_->next;
while(index --)
{
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkedNode* new_node = new LinkedNode(val);
new_node->next = dummy_head_->next;
dummy_head_->next = new_node;
size_++;
}
void addAtTail(int val) {
LinkedNode* new_node = new LinkedNode(val);
LinkedNode* cur = dummy_head_;
while(cur->next != NULL)
{
cur = cur->next;
}
cur->next = new_node;
size_++;
}
void addAtIndex(int index, int val) {
if(index > size_ || index < 0)
{
return;
}
LinkedNode* new_node = new LinkedNode(val);
LinkedNode* cur = dummy_head_;
while(index--)
{
cur = cur->next;
}
new_node->next = cur->next;
cur->next = new_node;
size_++;
}
void deleteAtIndex(int index) {
//这个边界条件少了一个=
if(index>=size_ || index <0)
{
return;
}
LinkedNode* cur = dummy_head_;
while(index--)
{
cur = cur->next;
}
LinkedNode* temp = cur->next;
cur->next = cur->next->next;
// delete temp;
size_--;
}
private:
LinkedNode* dummy_head_;
int 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);
*/
24.反转链表
这道题应该算比较基础的题。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
{
return head;
}
// prev
ListNode* prev = NULL;
// curr
ListNode* curr = head;
// temp
ListNode* temp;
while(curr)
{
temp = curr->next;
curr->next= prev;
prev = curr;
curr = temp;
}
return prev;
}
};