移除链表元素
我的解法:
注意细节:要删掉移除的元素。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head!=nullptr){
if(head->val==val){
head=head->next;
}
}
ListNode* nowhead = head;
while(nowhead){
if(nowhead->next->val == val){
if(nowhead->next->next == nullptr){
nowhead->next =nullptr;
}else{
nowhead->next=nowhead->next->next;
}
}
nowhead = nowhead->next;
}
return head;
}
};
//修改后
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head != NULL && head->val==val){
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* nowhead = head;
while(nowhead !=NULL && nowhead->next !=NULL ){
if(nowhead->next->val == val){
ListNode* tmp=nowhead->next;
nowhead->next=nowhead->next->next;
delete tmp;
}else{
nowhead = nowhead->next;
}
}
return head;
}
};
方法二:
增加一个伪头结点dummyhead,dummyhead->next = head;
这样可以统一头结点和后续节点的删除方式。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead = new ListNode(0);\\记得定义
dummyhead->next =head;
ListNode* nowhead =dummyhead;
while(nowhead !=NULL && nowhead->next !=NULL ){
if(nowhead->next->val == val){
ListNode* tmp=nowhead->next;
nowhead->next=nowhead->next->next;
delete tmp;
}else{
nowhead = nowhead->next;
}
}
return dummyhead->next;
}
};
反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while(cur!=nullptr){
ListNode * tmp = cur->next;
cur->next =prev;
prev =cur;
cur =tmp;
}
return prev;
}
};