Day 1
Date: September 24, 2022 12:31 PM
LinkedIn: https://leetcode.cn/problems/design-linked-list/
Title: 设计链表
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
struct Node{
int val;
struct Node *next;
};//数据节点
typedef struct {
int val;
int mount;
struct Node *head;
} MyLinkedList;//头节点
MyLinkedList* myLinkedListCreate() {
MyLinkedList *H=(MyLinkedList *)malloc(sizeof(MyLinkedList));
H->mount=0;
H->head=NULL;
return H;
}
int myLinkedListGet(MyLinkedList* obj, int index) {
struct Node *p=obj->head;//第一个节点
if(index>obj->mount||index<0){
return -1;
}
int value=-1;
int count=0;
while(p){
if(count==index){
value=p->val;
break;
}
p=p->next;
count++;
}
return value;
}
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
struct Node *q=(struct Node*)malloc(sizeof(struct Node));
q->val=val;
q->next=NULL;
if(obj->head==NULL){//头节点为空
obj->head=q;
}else{
q->next=obj->head;
obj->head=q;
}
obj->mount++;
}
void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
int cnt=0;
struct Node *p=obj->head;
struct Node *q =(struct Node *)malloc(sizeof(struct Node));
q->val=val;
q->next=NULL;
if(obj->head==NULL){//头节点为空
obj->head=q;
}else{
while(p->next){
p=p->next;
}
p->next=q;
}
obj->mount++;
}
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
if (obj->mount < index)
{
//插入的位置 大于节点的数量
return;
}
if (index <= 0)
{
myLinkedListAddAtHead(obj, val);
return;
}
struct Node* p = obj->head;//p、q为第一个数据节点
struct Node* q = obj->head;
int value = -1;
int count = 0; //从1开始 找到插入位置的前一个
while (p != NULL)
{
if (count >= index)
{
break;
}
q=p;//前驱
p = p->next;
count++;
}
if(count==0){
myLinkedListAddAtHead(obj,val);
}
else if(count==obj->mount){
myLinkedListAddAtTail(obj,val);
}else{
struct Node *w =(struct Node *)malloc(sizeof(struct Node));
w->val=val;
w->next=q-> next;
q->next=w;
obj->mount++;
}
}
void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
if(index>=0&&index<obj->mount){//index有效
struct Node *p=obj->head;
struct Node *q =obj->head;
int count=0;
while(p){
if(count==index){
break;
}
q=p;
p=p->next;
count++;
}
if(count==0){//obj中头节点空
obj->head=obj->head->next;
}else{
q->next=p->next;
}
free(p);
obj->mount--;
}
}
void myLinkedListFree(MyLinkedList* obj) {
struct Node *p=obj->head;
while(obj->mount){
struct Node *q =(struct Node *)malloc(sizeof(struct Node));
q=p;
p=p->next;
free(q);
obj->mount--;
}
free(obj);//释放obj
}