美文网首页
C中的链表

C中的链表

作者: simonycshi | 来源:发表于2019-03-25 11:45 被阅读0次

C中的链表

1. 声明和初始化

/* 节点结构和变量声明: */
struct node { 
    int value; 
    struct node *next; 
}; 
struct node *head, *temp;

/* 为新节点分配空间 */ 
//推荐分配内存语句与判断语句结合
if ((temp = (struct node *) malloc(sizeof(struct node))) == NULL) { 
    printf("Allocation failed.\n"); 
    exit(1); 
}

2. 访问节点元素

  1. (*temp).value = 47; (*temp).next = NULL;
  2. temp->value = 47; temp->next = NULL;(推荐)

3. 打印链表节点

  • /* 打印首节点为h的全部链表节点数据 */
    void print_list(struct node *h) { 
      if (h == NULL) { 
          printf("The list is empty.\n");
      } else { 
          printf("Values in the list are:\n"); 
          while (h != NULL) { 
          printf("%d\n", h->value); 
          h = h->next; 
          }
      } 
    }
    

4. 搜索链表节点

/* 返回指向搜索到节点的指针,若没有返回NULL */ 
struct node *search_list(struct node *h, int x) {
    while (h != NULL) { 
    if (h->value == x) {
        return h; 
    }
    h = h->next; 
    }
  return NULL; 
}

5. 插入节点

  • 为什么使用二重指针struct node **h:我们需要操作的节点本身是一个结构体(用指向堆上内存的指针表示*h*t),我们需要指向节点的指针就是一个二重指针
/* 创建一个值为v的新节点,并添加到首节点为*h,尾节点为*t的链表尾部 */ 
void insert_node (struct node **h, struct node **t, int v) {
    struct node *temp;

    if ((temp = (struct node *)malloc(sizeof(struct node))) == NULL) {              
    printf("Node allocation failed. \n"); 
        exit(1); 
    /* 申请内存失败,终止程序 */ 
    } 
  
  /* 将v拷贝进节点 */ 
    temp->value = v; 
  temp->next = NULL; 
  if (*h == NULL) { 
    /* 如果是空链表 */ 
    *h = *t = temp; 
  } else { 
    /* 非空链表,添加在*t尾部 */  
    (*t)->next = temp; 
    *t = (*t)->next; 
  } 
}

5. 使用typedef来简化

typedef struct node { 
  int value; 
  struct node *next; 
} NODE, *PTRNODE;

在以上声明中:

  • NODE 表示struct node
  • PTRNODE 表示struct node *
  • eg. NODE x; PTRNODE head, tail;

相关文章

  • C中的链表

    C中的链表 1. 声明和初始化 2. 访问节点元素 (*temp).value = 47; (*temp).nex...

  • 容器(2) - LinkedList

    LinkedList 基本实现 LinkedList 类似 C/C++ 的双向链表,这种链表中任意一个存储单元都可...

  • 单链表 C++

    单链表 C++ 题目 1、创建单链表2、初始化单链表3、释放单链表4、获取单链表中元素的数量5、输出单链表中的所有...

  • C++语言实现双向链表

    这篇文章是关于利用C++模板的方式实现的双向链表以及双向链表的基本操作,在之前的博文C语言实现双向链表中,已经给大...

  • 链表

    单链表 C实现 Java实现 双链表 C实现 Java实现

  • 链表常见面试题

    单链表的创建和遍历 求单链表中节点的个数 注意检查链表是否为空。时间复杂度为O(n)。 https://www.c...

  • 单向链表的链式实现

    Note 使用的工具是CodeBlocks 16.01 启用了C99标准 单向链表是这样是个序列:对于单向链表中的...

  • LeetCode第二题 C 链表

    c语言链表详解(超详细) 链表就是N个结构体链表都有一个头指针,一般以head来表示,存放的是一个地址。链表中的节...

  • python 实现单向链表的倒序

    本文适合有一定数据结构基础的人阅读(就是你要懂链表是什么)在C/C++中,通常采用“指针+结构体”来实现链表;而在...

  • C# 链表

    链表介绍 Unity 用C#写的链表类 简述链表和数组的区别 Unity--链表实现贪吃蛇

网友评论

      本文标题:C中的链表

      本文链接:https://www.haomeiwen.com/subject/wvdvvqtx.html