个人博客主页:https://blog.csdn.net/2301_79293429?type=blog
专栏:https://blog.csdn.net/2301_79293429/category_12545690.html
题目链接:
707. 设计链表 - 力扣(LeetCode)
该题为中等题,包括了对链表的大部分常用操作,更改真的很烦,因为它很长,链表题目也不方便调试,不知道哪里有问题,你只有一点一点的对比代码才找得到错哪
AC代码:
/*一定要建立虚拟头节点,方便的多--->统一操作,避免每次都要将头节点单独讨论*/
typedef int VALTYPE;/*方便更改数据类型*/
/*链表的基本创建*/
typedef struct MyLinkedList {
VALTYPE val;
struct MyLinkedList* next;
}MyLinkedList;
MyLinkedList* myLinkedListCreate()
{
MyLinkedList* head=(MyLinkedList*)malloc(sizeof(MyLinkedList));
head->val=0;
head->next=NULL;
return head;
}
int myLinkedListGet(MyLinkedList* obj, int index)
{
/*这里的obj是我们创建的虚拟头节点,所以要令p=obj->next*/
MyLinkedList* p=obj->next;
/*只是创建了一个指针变量,不需要动态开辟一块空间*/
int i;
for(i=0;p!=NULL;i++)
{
if(i==index)
return p->val;
if(p->next==NULL)
return -1;
p=p->next;
}
return -1;
}
void myLinkedListAddAtHead(MyLinkedList* obj, int val)
{
MyLinkedList* p1=(MyLinkedList*)malloc(sizeof(MyLinkedList));
/*创建了一个结构体,需要动态开辟一块空间*/
p1->val=val;
p1->next=obj->next;
/*注意顺序,要先将新节点的next指向obj的next,再更新obj的next*/
obj->next=p1;
}
void myLinkedListAddAtTail(MyLinkedList* obj, int val)
{
/*正确写法*/
MyLinkedList* p=obj;/*不是obj->next了,因为也要对头节点进行判断是否为null*/
for(int i=0;p->next!=NULL;i++)
{ /**/
p=p->next;
}
MyLinkedList* p1=(MyLinkedList*)malloc(sizeof(MyLinkedList));
p1->next=NULL;
p1->val=val;
p->next=p1;
}
void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val)
{
if (index == 0) /**/
{
myLinkedListAddAtHead(obj, val);
return;
}
MyLinkedList* p=obj->next;
for(int i=1;p!=NULL;i++)
{/*要从1开始,0要特殊处理*/
if(i==index)
{/*要等于index*/
MyLinkedList* p2=(MyLinkedList*)malloc(sizeof(MyLinkedList));
p2->val=val;
p2->next=p->next;
p->next=p2;
return;/*直接return*/
}
p=p->next;
}
void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index)
{
MyLinkedList* p=obj;
for(int i=-1;p!=NULL&&p->next!=NULL;i++)
{
if(i==index-1)
{
MyLinkedList* temp=p->next;
p->next=p->next->next;
free(temp);
break;
}
p=p->next;
}
}
void myLinkedListFree(MyLinkedList* obj)
{
struct MyLinkedList*p=obj->next;
for(int i=0;p!=NULL;i++)
{
struct MyLinkedList*temp=p;
p=p->next;
free(temp);
}
}
/**
* Your MyLinkedList struct will be instantiated and called as such:
* MyLinkedList* obj = myLinkedListCreate();
* int param_1 = myLinkedListGet(obj, index);
* myLinkedListAddAtHead(obj, val);
* myLinkedListAddAtTail(obj, val);
* myLinkedListAddAtIndex(obj, index, val);
* myLinkedListDeleteAtIndex(obj, index);
* myLinkedListFree(obj);
*/
最后祝大家题题AC,只盼做个WA梦 ~