该题目覆盖了链表的常见操作,非常适合初学者巩固链表相关知识。 leetocde原题链接
typedef struct {
int val;
struct MyLinkedList *next;
} MyLinkedList;
MyLinkedList* myLinkedListCreate()
{
MyLinkedList* head = (MyLinkedList *)malloc(sizeof (MyLinkedList));
head->next = NULL;
return head;
}
int myLinkedListGet(MyLinkedList* obj, int index)
{
int i = 0;
if(obj->next == NULL)
return -1;
MyLinkedList *p = obj->next;
while(true)
{
if (i == index)
return p->val;
p = p->next;
i++;
if (p == NULL)
return -1;
}
return 0;
}
void myLinkedListAddAtHead(MyLinkedList* obj, int val)
{
MyLinkedList *p = (MyLinkedList *)malloc(sizeof(MyLinkedList));
p->val = val;
p->next = obj->next;
obj->next = p;
}
void myLinkedListAddAtTail(MyLinkedList* obj, int val)
{
MyLinkedList *t = obj;
MyLinkedList *p = (MyLinkedList *)malloc(sizeof(MyLinkedList));
while(t->next)
{
t = t->next;
}
p->val = val;
t->next = p;
p->next = NULL;
}
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val)
{
MyLinkedList *t = obj;
MyLinkedList *p = (MyLinkedList *)malloc(sizeof(MyLinkedList));
p->val = val;
int i = 0;
if(index <= 0)
{
p->next = obj->next;
obj->next = p;
}
else if(index > 0)
{
for(i = 1; t!= NULL; i++)
{
t = t->next;
if(index == i && t->next != NULL)
{
p->next = t->next;
t->next = p;
}
if(index == i && t->next == NULL)
{
p->next = NULL;
t->next = p;
}
}
}
}
void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index)
{
MyLinkedList *t = obj->next, *c = obj;
int i = 0;
while(t->next != NULL)
{
if(index == i)
{
c->next = t->next;
free(t);
return;
}
t = t->next;
c = c->next;
i++;
}
if(index == i)
{
c->next = NULL;
free(t);
}
}
void myLinkedListFree(MyLinkedList* obj)
{
while(obj != NULL)
{
MyLinkedList *t = obj;
obj = obj->next;
free(t);
}
}
|