【203】 移除链表元素
cpp
/**
* 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* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(0, head);
ListNode* temp = dummy;
while(temp->next){
if(temp->next->val == val){
temp->next = temp->next->next;
}else{
temp = temp->next;
}
}
return dummy->next;
}
};
time:23:26
【206】反转链表
cpp
// 将一个个结点取出,重新组成链表
/**
* 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) {
ListNode* dummy_Node = new ListNode(0, head);
while(head != NULL && head->next != NULL){
ListNode* dnext = dummy_Node->next;
ListNode* hnext = head->next;
dummy_Node->next = hnext;
head->next = hnext->next;
hnext->next = dnext;
}
return dummy_Node->next;
}
};
time:30
总结:应理解dummy_Node的含义,指向头结点的哑节点。