203 移除链表元素
/**
-
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 *p = head;
ListNode *q = NULL;
if(head != nullptr)
{
q = p->next;
}
while(q != NULL)
{
if(q->val == val)
{
ListNode *tmp = q->next;
p->next = q->next;q = tmp; } else { p = p->next; q= q->next; } } if(head != nullptr) { ListNode *temp = head->next; if(head->val == val) { head = temp; } } return head;
}
};
设计链表
class MyLinkedList {
public:
struct ListNode{
int val;
ListNode *next;
ListNode(int val):val(val), next(nullptr){}
};
MyLinkedList()
{
_head = new ListNode(0);
_size = 0;
}int get(int index)
{
if(index > (_size - 1) || index < 0)
{
return -1;
}
ListNode *cur = _head->next;
for(int i = 0; i < index; ++i)
{
cur = cur->next;
}
return cur->val;
}void addAtHead(int val)
{
ListNode *tmp = new ListNode(val);
if(_size == 0)
{
_head->next =tmp;
}
else
{
tmp->next = _head->next;
_head->next = tmp;
}
_size++;
}void addAtTail(int val)
{
ListNode *tmp = new ListNode(val);
ListNode *cur = _head;
for(int i = 0; i < _size; ++i)
{
cur = cur->next;
}
cur->next = tmp;
++_size;
}void addAtIndex(int index, int val)
{
if(index > _size) return;
if(index < 0) index = 0;
ListNode *tmp = new ListNode(val);
ListNode *p = _head;
for(int i = 0; i < index; ++i)
{
p = p->next;
}
tmp->next = p->next;
p->next = tmp;
++_size;
}void deleteAtIndex(int index)
{
if (index >= _size || index < 0) {
return;
}
ListNode *p = _head;
for(int i = 0; i < index; ++i)
{
p = p->next;
}
ListNode *tmp = p->next;
p->next = tmp->next;
delete tmp;
tmp = nullptr;
--_size;
}void printLinkedList() {
ListNode* cur = _head;
while (cur->next != nullptr) {
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
int _size;
ListNode *_head;
};
反转链表
使用头插法
/**
- 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 reverseList(ListNode* head) {
ListNode *p = head;
ListNode *q = nullptr;
if(head)
{
q = head->next;
}
while(q)
{
ListNode *tmp = q->next;
q->next = head;
p->next = tmp;
head = q;
q = p->next;
}
return head;
}
};