203.移除連結串列元素**707.設計連結串列206.反轉連結串列**
203.移除連結串列元素
題目地址 : https://leetcode.cn/problems/remove-linked-list-elements/submissions/541762363/
程式碼 :
/**
* 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;
ListNode* pre;
ListNode* LinkedList_Return;
p = head ;
LinkedList_Return = nullptr;
pre = p;
while( p != nullptr )
{
if(p->val == val)
{
pre->next = p->next;
pre = pre ;
}
else if(LinkedList_Return == nullptr)
{
LinkedList_Return = p;
pre = p; // 要 區分 情況
}
else // 注意 情況 分類
{
pre = p;
}
p = p->next;
}
return LinkedList_Return ;
}
};
707.設計連結串列
題目地址 : https://leetcode.cn/problems/design-linked-list/
程式碼 :
class MyLinkedList {
public:
struct LinkedList
{
int val;
LinkedList * next;
};
LinkedList * head = nullptr ;
int length_LinkedList;
MyLinkedList() {
length_LinkedList = 0;
}
int get(int index) {
LinkedList * p ;
p = head ;
int count_Index = 0;
if(index < 0 || index >= length_LinkedList)
{
return -1 ;
}
while( p != nullptr && count_Index < index )
{
p = p->next;
count_Index++;
}
if(count_Index < index )
{
return -1;
}
return p->val ;
}
void addAtHead(int val) {
if(head == nullptr)
{
LinkedList * temp = (LinkedList *) malloc (sizeof (LinkedList));
temp->val = val;
temp->next = nullptr;
head = temp;
}
else
{
LinkedList * p = head;
LinkedList * temp = (LinkedList *) malloc (sizeof (LinkedList));
temp->val = val;
temp->next = head;
head = temp;
}
length_LinkedList