赞
踩
文章链接:https://programmercarl.com/%E9%93%BE%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html
设置虚拟头节点,方便对头节点是需要移除的情况做处理。
当遍历指针的下一个节点值为目标值时,用tmp存储下一个节点,将当前遍历指针的next修改为tmp的next,之后删除tmp指向的内存。
如果不是,cur = cur->next;
最后的头节点是dummynode的next节点,将头节点指向dummynode->next,删除dummynode,返回头节点.
ListNode* removeElements(ListNode* head, int val) { ListNode* dummynode = new ListNode(-1,head); ListNode* cur = dummynode; while(cur->next != nullptr){ if(cur->next->val == val){ ListNode* tmp = cur->next; cur->next = tmp->next; delete tmp; } else{ cur = cur->next; } } head = dummynode->next; delete dummynode; return head; }
题目链接/文章讲解/视频讲解::https://programmercarl.com/0203.%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1%A8%E5%85%83%E7%B4%A0.html
抄了但错,明天改
更新:删除节点时没有考虑index == size的情况,因为index从0开始,所以index ==size时已经溢出了
class MyLinkedList { public: struct LinkNode{ int val; LinkNode* next; LinkNode(int val):val(val),next(nullptr){} }; MyLinkedList() { _dummynode = new LinkNode(0); _size = 0; } int get(int index) { if(index>(_size-1)||index<0){ return -1; } LinkNode* cur = _dummynode->next; while(index--){ cur = cur->next; } return cur->val; } void addAtHead(int val) { LinkNode*newnode = new LinkNode(val); newnode->next = _dummynode->next; _dummynode->next = newnode; _size++; } void addAtTail(int val) { LinkNode* newnode = new LinkNode(val); LinkNode* cur = _dummynode; while(cur->next!=nullptr){ cur = cur->next; } cur->next = newnode; _size++; } void addAtIndex(int index, int val) { if(index>_size) return; if(index<0) index = 0; LinkNode*newnode = new LinkNode(val); LinkNode*cur = _dummynode; while(index--){ cur = cur->next; } newnode->next = cur->next; cur->next = newnode; _size++; } void deleteAtIndex(int index) { if(index >= _size||index < 0){ return; } LinkNode*cur = _dummynode; while(index--){ cur = cur->next; } LinkNode* tmp = cur->next; cur->next = tmp->next; delete tmp; tmp = nullptr; _size--; } private: LinkNode* _dummynode; int _size; };
题目链接/文章讲解/视频讲解:https://programmercarl.com/0206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.html
反转链表,写了八百遍忘了八百遍,再写第八百零一遍
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr,*tmp;
while(head!=nullptr){
tmp = head->next;
head->next = pre;
pre = head;
head =tmp;
}
return pre;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。