当前位置:   article > 正文

数据结构——单向链表的实现(C语言)_c语言 用数组实现单向链表

c语言 用数组实现单向链表

如图所示,可以看到组成链表的部分是一个个包含有元素和指针的结构体组成的,其中每一个结构体包含了本身所存储的元素,以及一个指向下一个结构体的指针,通过这种单项链表的结构,在插入与删除元素的操作复杂度上,相比于简单的数组要简单得多。因为,对于数组元素的插入和删除,对于其后续的元素都需要进行相移的前移或者后移,而链表只需要在该元素的前节点和后节点进行指针的改写(或存在元素的释放),即可完成操作

当然相比可以进行随机访问的数组而言,只能进行顺序访问的链表就显得有些繁琐,链表的访问需要通过由头节点通过指针进行顺序查找。

以下为单向链表实现代码

链表定义与初始化函数:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef int E;
  4. struct ListNode{
  5. E element;
  6. struct ListNode * next;
  7. };
  8. typedef struct ListNode * ArrayNode;
  9. void initListNode(ArrayNode node){
  10. node->next = NULL;
  11. }

插入链表元素函数:

  1. _Bool insertNode(ArrayNode head, E element, int index){
  2. if (index < 1) return 0;
  3. while (--index){
  4. head = head->next;
  5. if (head == NULL) return 0;
  6. }
  7. ArrayNode newhead = malloc(sizeof(struct ListNode));
  8. if(newhead == NULL) return 0;
  9. newhead->element=element;
  10. if(head->next != NULL){
  11. newhead->next = head->next;
  12. }
  13. head->next = newhead;
  14. return 1;
  15. }

此处采用malloc函数对新元素空间进行申请,并且对删除节点是否为尾节点进行判断,减少操作

删除链表元素函数:

  1. _Bool deleteNode(ArrayNode head, int index){
  2. if(index<1) return 0;
  3. while(--index){
  4. head = head->next;
  5. if(head == NULL) return 0;
  6. }
  7. ArrayNode tmp = head->next;
  8. head->next=head->next->next;
  9. free(tmp);
  10. return 1;
  11. }

按顺序打印链表所有元素:

  1. void printList(ArrayNode node){
  2. while(node->next){
  3. node = node->next;
  4. printf("%d\n", node->element);
  5.         printf("\n");
  6. }
  7. }

主函数测试:

  1. int main(){
  2. struct ListNode head;
  3. initListNode(&head);
  4. int i;
  5. for(i=1; i<5; ++i){
  6. insertNode(&head, i*100, i);
  7. }
  8. printList(&head);
  9. deleteNode(&head, 2);
  10. printList(&head);
  11. }

得到测试结果:

  1. 100
  2. 200
  3. 300
  4. 400
  5. 100
  6. 300
  7. 400

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/427979
推荐阅读
相关标签
  

闽ICP备14008679号