单链表一[带头节点链表]
单链表实现分带头节点链表和不带头节点链表:
使用头文件如下:
structLinkNode{void*x;structLinkNode*next;};
一,带头节点的链表:
1,链表创建
程序说明:
1)函数调用形式:szyu_link_create0("AA", "BB", NULL);其中NULL结尾是在for循环的判断结束条件为x == NULL。使用NULL可以是for循环正常退出
2)程序先创建头节点head,并初始化head节点
3)声明指向尾节点的last,并用head进行初始化。
4)for循环中第一次使用的x是入参中的x。
5)初始化新增节点,并将尾节点的next指针指向新增节点。并将尾节点指向新增节点
6)使用了va_start()记得结尾使用va_end()
7)新增第一个节点时使用last->next = node。此时的last和head是相等的。相当于head->next = node。
structLinkNode*szyu_link_create0(void*x,...){structLinkNode*head=NULL;head=(structLinkNode*)malloc(sizeof(structLinkNode));if(head==NULL){returnhead;}head->next=NULL;structLinkNode*last=head;va_listargs;va_start(args,x);for(;x;x=va_arg(args,void*)){structLinkNode*node=NULL;node=(structLinkNode*)malloc(sizeof(structLinkNode));if(node==NULL){returnhead;}node->x=x;node->next=NULL;last->next=node;last=node;}va_end(args);returnhead;}
2,链表插入
程序说明:
1)key < 1保证插入的下标不能出现比一小;key - 1 > len保证在链表最后面能插入节点。
2)cnt = 1而不是0是保证节点停留在插入位置的前一节点。
3)添加节点到相应的位置即可。
structLinkNode*szyu_link_insert0(structLinkNode*head,void*x,intkey){if(head==NULL){returnhead;}intlen=szyu_link_length(head);if(key<1||key-1>len){returnhead;}structLinkNode*insert=head;intcnt=1;for(;cnt<key;cnt++){insert=insert->next;}structLinkNode*node=NULL;node=(structLinkNode*)malloc(sizeof(structLinkNode));if(node==NULL){returnhead;}node->x=x;node->next=insert->next;insert->next=node;returnhead;}
3,链表长度获取
程序说明:
1)过掉头节点,再开始获取长度。
intszyu_link_length(structLinkNode*head){if(head==NULL){return0;}structLinkNode*plen=head->next;intlength=0;for(;plen!=NULL;plen=plen->next){length++;}returnlength;}
4,链表打印:
程序说明:
1)如果链表为空,获取只有头节点,则直接返回。
2)输出时,由于结构体存的void *,故输出需进行类型转换才行。
voidszyu_link_print0(structLinkNode*head){if(head==NULL||head->next==NULL){return;}structLinkNode*print=head->next;intlen;for(len=0;print!=NULL;print=print->next){printf("%s",(char*)print->x);}printf("\n");}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。