C中的链表

2019-03-25  本文已影响0人  simonycshi

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. 打印链表节点

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. 插入节点

/* 创建一个值为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;

在以上声明中:

上一篇 下一篇

猜你喜欢

热点阅读