在链表初创之时,并没有自建一个无意义的头结点,但随着发现创建了“无意义”的头结点之后整个代码简谐了,但在应试中大家还是要求自主实现不带头结点的链表功能。 可以对比下有头结点和无头结点代码的美观性和可读性,附上无头结点的代码: https://blog.csdn.net/weixin_54057383/article/details/119151365
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define TYPE int
typedef struct Node
{
TYPE data;
struct Node* next;
}Node;
Node* create_node(TYPE data)
{
Node* node = malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
void add_head_list(Node* head,TYPE data)
{
Node* node = create_node(data);
node->next = head->next;
head->next = node;
}
void add_tail_list(Node* head,TYPE data)
{
while(NULL != head->next) head = head->next;
head->next = create_node(data);
}
void show_list(Node* head)
{
while(NULL != head->next)
{
printf("%d ",head->next->data);
head = head->next;
}
printf("\n");
}
bool del_head_list(Node* head)
{
if(NULL == head->next)
return false;
Node* temp = head->next;
head->next = temp->next;
free(temp);
return true;
}
bool del_tail_list(Node* head)
{
while(NULL!=head->next && NULL!=head->next->next)
head = head->next;
return del_head_list(head);
}
bool del_value_list(Node* head,TYPE data)
{
while(NULL!=head->next && data!=head->next->data)
head = head->next;
return del_head_list(head);
}
bool del_index_list(Node* head,size_t index)
{
while(NULL!=head->next && index--)
head = head->next;
return del_head_list(head);
}
bool insert_list(Node* head,size_t index,TYPE data)
{
while(NULL!=head->next)
{
if(0 == index--)
{
add_head_list(head,data);
return true;
}
head = head->next;
}
return false;
}
Node* _query_list(Node* head,TYPE key)
{
while(NULL != head->next)
{
head = head->next;
if(key == head->data)
return head;
}
return NULL;
}
int query_list(Node* head,TYPE key)
{
for(int i=0; NULL!=head->next; i++)
{
head = head->next;
if(key == head->data)
return i;
}
return -1;
}
bool modify_index_list(Node* head,size_t index,TYPE new)
{
while(NULL!=head->next)
{
head = head->next;
if(0 == index--)
{
head->data = new;
return true;
}
}
return false;
}
bool modify_value_list(Node* head,TYPE old,TYPE new)
{
Node* node = _query_list(head,old);
if(NULL == node)
return false;
node->data = new;
return true;
}
void sort_list(Node* head)
{
Node* end = NULL;
for(Node* i=head->next,*j; i->next!=NULL; i=i->next)
{
for(j=head->next; j->next!=end; j=j->next)
{
if(j->data > j->next->data)
{
TYPE temp = j->data;
j->data = j->next->data;
j->next->data = temp;
}
}
end = j;
}
}
size_t size_list(Node* head)
{
size_t size = 0;
while(NULL != head->next)
{
size++;
head = head->next;
}
return size;
}
void destroy_list(Node* head)
{
while(del_head_list(head));
}
int main(int argc,const char* argv[])
{
Node* head = create_node(0);
for(int i=0; i<10; i++)
{
add_tail_list(head,i);
}
insert_list(head,1,100);
show_list(head);
printf("%d\n",query_list(head,100));
modify_index_list(head,9,0);
sort_list(head);
show_list(head);
}
|