题目链接:203.移除链表元素
思路:在首元节点前设置一个头结点,就不需要对首元节点和后面的节点分开做操作了
代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next=head;
ListNode* ptr=dummyhead;
while(ptr->next){
if(ptr->next->val==val){
ListNode* tmp=ptr->next;
ptr->next=ptr->next->next;
delete tmp;
}
else ptr=ptr->next;
}
head=dummyhead->next;
delete dummyhead;
return head;
}
};
题目链接: 707.设计链表
代码:
class MyLinkedList {
public:
struct ListNode{
int val;
ListNode* next;
ListNode(int val):val(val),next(nullptr){};
};
int size;
ListNode* dummyhead;
MyLinkedList() {
size=0;
dummyhead=new ListNode(0);
}
int get(int index) {
if(index<0 || index>=size){
return -1;
}
ListNode* cur=dummyhead->next;
while(index--){
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* node=new ListNode(val);
node->next=dummyhead->next;
dummyhead->next=node;
size++;
}
void addAtTail(int val) {
ListNode* cur=dummyhead;
while(cur->next){
cur=cur->next;
}
ListNode* node=new ListNode(val);
node->next=cur->next;
cur->next=node;
size++;
}
void addAtIndex(int index, int val) {
if(index>size) return;
if(index<0) index=0;
ListNode* node = new ListNode(val);
ListNode* cur=dummyhead;
while(index--){
cur=cur->next;
}
node->next=cur->next;
cur->next=node;
size++;
}
void deleteAtIndex(int index) {
if(index>=size||index<0) return;
ListNode* cur=dummyhead;
while(index--){
cur=cur->next;
}
ListNode* tmp=cur->next;
cur->next=tmp->next;
delete tmp;
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);
*/
代码链接 :206.翻转链表
思路:每次遍历一个节点(cur),要让他指向前一个节点(pre),指向前一个节点后本身的指向消失,所以要用tmp存下cur->next
代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tmp;
ListNode* cur=head;
ListNode* pre=NULL;
while(cur){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
};