- 接上一篇博客内容:
https://blog.csdn.net/xiaolz88/article/details/119194749 上一篇讲的是线性表的数组方式实现,接下来是使用链表对实现线性表; 废话不多说,直接上代码:
typedef void Linklist;
typedef struct _tag_linklistnode
{
struct _tag_linklistnode *next;
}LinklistNode;
Linklist *Linklist_Create(void);
int Linklist_Insert(Linklist* list,LinklistNode* node, int pos);
LinklistNode* Linklist_delete(Linklist*list,int pos);
LinklistNode* Linklist_get(Linklist *list, int pos);
int Linklist_length(Linklist* list);
void Linklist_destory(Linklist* list);
int linklist_clear(Linklist* list);
具体实现:
typedef struct
{
LinklistNode head;
int length;
}TLinklist;
Linklist *Linklist_Create(void)
{
TLinklist *tlinklist = (TLinklist *)malloc(sizeof(TLinklist));
if(tlinklist == NULL)
{
printf("err:malloc\n");
return NULL;
}
tlinklist->head.next = NULL;
tlinklist->length = 0;
return (Linklist*)tlinklist;
}
int Linklist_Insert(Linklist* list,LinklistNode* node, int pos)
{
TLinklist *tlink = NULL;
int i = 0;
if(list == NULL || node == NULL || pos < 0)
{
printf("Linklist_Insert error\n");
return -1;
}
tlink = (TLinklist*)list;
LinklistNode *current = &(tlink->head);
for(i = 0; i < pos ; i++)
{
current = current->next;
}
node->next = current->next;
current->next = node;
tlink->length++;
return 0;
}
LinklistNode* Linklist_delete(Linklist*list,int pos)
{
TLinklist *tlink = NULL;
int i = 0;
LinklistNode *current = NULL;
LinklistNode *tmp = NULL;
if(list == NULL || pos < 0)
{
printf("input param error\n");
return NULL;
}
tlink = (TLinklist *)list;
current = &(tlink->head);
for( i = 0; i < pos && (current->next != NULL); i++)
{
current = current->next;
}
tmp = current->next;
current ->next = tmp->next;
tlink->length--;
return tmp;
}
LinklistNode* Linklist_get(Linklist *list, int pos)
{
TLinklist *tlink = NULL;
int i = 0;
LinklistNode *current = NULL;
LinklistNode *tmp = NULL;
if(list == NULL || pos < 0)
{
printf("input param error\n");
return NULL;
}
tlink = (TLinklist *)list;
current = &(tlink->head);
for(int i = 0; i< pos && (current->next != NULL); i++)
{
current = current->next;
}
return current->next;
}
int Linklist_length(Linklist* list)
{
TLinklist *tlink = NULL;
if(list == NULL)
{
printf("input param error\n");
return -1;
}
tlink = (TLinklist *)list;
return tlink->length;
}
void Linklist_destory(Linklist* list)
{
if(list != NULL)
{
free(list);
list = NULL;
}
return ;
}
int linklist_reset(Linklist* list)
{
TLinklist *tlink = NULL;
if(list == NULL)
{
return -1;
}
tlink = (TLinklist*)list;
tlink->head.next = NULL;
tlink->length = 0;
return 0;
}
总结:带有头结点的链表, 遍历链表时,首先将辅助指针变量指向头结点,然后移动pos次, 辅助指针变量指向第n-1个元素,所以每次遍历返回的是ret = current->next;
|