第二章 链表part01
第二章 链表part01
203.移除链表元素
题目链接: https://leetcode.cn/problems/remove-linked-list-elements/
Code :
/**
* 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* pre;
ListNode* NewHead;
while(p != nullptr && p->val == val)
{
p = p->next;
}
NewHead = p;
pre = p;
while(p != nullptr)
{
//内循环
if(p->val == val)
{
pre->next = p->next;
}
else
{
pre = p;
}
p = p->next;
}
return NewHead;
}
};
707. 设计链表
题目链接: https://leetcode.cn/problems/design-linked-list/
Code
class MyLinkedList {
public:
struct node
{
int val;
node * next;
};
// 带头 结点
node * head ;
MyLinkedList() {
head = new node() ;
head->val = 0;
head->next = NULL;
}
int get(int index) {
int i = 0;
//cout<<"------------get--------------------"<<endl;
int step = index + 1;
int count = 0;
node * p;
p = head->next;
//cout<<"index : "<<index<<endl;
//cout<<"step : "<<step<<endl;
//cout<<"head->val : "<<head->val<<endl;
if(step > head->val)
{
return -1;
}
if(step == 1)
{
return p->val;
}
count++;
for( ; i < (step - 1) ; i++ )
{
if(p == NULL)
{
break;
}
p = p->next;
count++;
}
//cout<<"------count : "<<count<<endl;
if(count < (step))
{
return -1;
}else
if(count == step)
{
return p->val;
}
else
{
cout<<"step 溢出"<<endl;
return -1;
}
//cout<<"-----------------------------------"<<endl;
}
void addAtHead(int
