赞
踩
分为两步:
更新头结点;
更新非头结点
/** * 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) { while(head != NULL && head->val == val){ ListNode* tmp = head; head = head->next; delete tmp; } ListNode* node = head; while(node != NULL && node->next != NULL) { if(node->next->val == val) { ListNode* tmp = node->next; node->next = node->next->next; delete tmp; } else{ node = node->next; } } return head; } };
此题目在于考察链表的基本操作,需要熟练掌握
class MyLinkedList { public: struct LinkNode{ int val; LinkNode* next; LinkNode(int val): val(val), next(NULL){} }; MyLinkedList() { _dummyHead = new LinkNode(0); //虚拟头结点 _size = 0; } int get(int index) { int result = -1; if(index < _size && index >= 0) { LinkNode* cur = _dummyHead->next; //for(int i = 0; i <= index; i++) while(index--) { cur = cur->next; } result = cur->val; } return result; } void addAtHead(int val) { LinkNode* oldhead =_dummyHead->next; LinkNode* newhead = new LinkNode(val); _dummyHead->next = newhead; newhead->next = oldhead; _size++; } void addAtTail(int val) { LinkNode* endnode =_dummyHead; while(endnode->next != NULL) { endnode = endnode->next; } LinkNode* newnode = new LinkNode(val); endnode->next = newnode; newnode->next = NULL; _size++; } void addAtIndex(int index, int val) { index = index < 0 ? 0 : index; if(index == _size ) { //addAtTail(val); LinkNode* endnode =_dummyHead; while(endnode->next != NULL) { endnode = endnode->next; } LinkNode* newnode = new LinkNode(val); endnode->next = newnode; newnode->next = NULL; _size++; } else if(index < _size ) { LinkNode* curnode =_dummyHead; int i = 0; while(i < index) { curnode = curnode->next; i++; } LinkNode* curnode2 = curnode->next; LinkNode* newnode = new LinkNode(val); curnode->next = newnode; newnode->next = curnode2; _size++; } } void deleteAtIndex(int index) { if(index > -1 && index < _size) { LinkNode* curnode =_dummyHead; int i = 0; while(i < index ) { curnode = curnode->next; i++; } LinkNode* tmp = curnode->next; if(index == _size - 1) { curnode->next = NULL; } else { curnode->next = tmp->next; } //curnode->next = tmp->next; delete tmp; tmp = NULL; _size--; } } private: // 单链表的私有成员变量:(虚拟头结点)、链表长度 // 其余的结点可通过头结点追寻 LinkNode* _dummyHead; // 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); */
对链表的基本构造不太熟悉,注意多多复习
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。