代码随想录刷题第三天
移除链表元素
/**
* 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 *dummyhead = new ListNode();
dummyhead->next = head;
ListNode *cur = dummyhead;
while (cur->next != nullptr)
{
if (cur->next->val == val)
{
cur->next = cur->next->next;
}else{
cur = cur->next;
}
}
return dummyhead->next;
// return head;
}
};
就是正常的删除链表的基本操作,记得新建一个新的虚拟节点
设计链表
class MyLinkedList {
public:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x): val(x),next(nullptr){}
};
MyLinkedList() {
dummyhead = new ListNode(0);
size = 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 *node = new ListNode(val);
ListNode *cur = dummyhead;
int size_tmp= size;
while (size_tmp--)
{
cur = cur->next;
}
cur->next = node;
size++;
}
void addAtIndex(int index, int val) {
if (index > size )
{
return;
}
ListNode *node = new ListNode(val);
ListNode *cur = dummyhead;
if (index < 0)
{
node->next = cur->next;
cur->next = node;
return ;
}
while (index--)
{
cur = cur->next;
}
node->next = cur->next;
cur->next = node;
size++;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= size)
{
return ;
}
ListNode *cur = dummyhead;
while (index--)
{
cur = cur->next;
}
cur->next = cur->next->next;
size--;
}
private:
int size;
ListNode *dummyhead;
};
虚拟节点还有链表长度是很关键的点,加上后代码变得简洁很多
反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr)
{
return head;
}
ListNode *pre = nullptr;
ListNode *tmp ;
ListNode *cur = head;
while (cur->next != nullptr)
{
tmp = cur->next;
cur->next = pre ;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
};
不要忘记空链表的情况,前面要加一个判断
本文介绍了如何在链表中进行元素删除,包括使用虚拟节点简化操作。同时展示了如何设计一个链表类,包含添加、获取、删除元素等方法。此外,还讨论了反转链表的算法,需要注意空链表的情况。
324

被折叠的 条评论
为什么被折叠?



