• C语言实现双链表(带头节点)


    双链表和单链表性质相似只是在多加了一个前指针

    1.定义结构体

    typedef struct Node{
      int data;
      struct Node *prior;
      struct Node *next;
    }Node,*LinkedList;

    2.比单链表一个指向

    LNew->data = i;
    L->next = LNew;
    LNew->prior = L; // 比单链表多这一条
    LNew->next = NULL;
    L = LNew;

    具体实现demo.c

    #include <stdio.h>
    #include <malloc.h>
    #include <stdlib.h>
    
    typedef struct Node{
      int data;
      struct Node *prior;
      struct Node *next;
    }Node,*LinkedList;
    
    LinkedList LinkedListInt(){
      Node *Head,*L,*LNew;
      int i;
      Head = (Node *)malloc(sizeof(Node));
      if(Head == NULL){
        printf("申请空间失败
    ");
        exit(-1);
      }
    
      L = Head;
      L->next = NULL;
    
      for(i=0;i<5;i++){
        LNew = (Node *)malloc(sizeof(Node));
        if(LNew == NULL){
          printf("申请空间失败
    ");
          exit(-1);
        }
    
        LNew->data = i;
        L->next = LNew;
          LNew->prior = L;
        LNew->next = NULL;
        L = LNew;
      }
    
      return Head;
    }
    
    int main(int argc, char const *argv[]) {
      /* code */
      Node *p;
      int i;
      p = LinkedListInt();
      p = p->next;
      // 让p的前指针指向p,这样第一个有值元素就有前指针
      p->prior = p;
    
      while(p != NULL){
        //printf("%d,",p->prior->data);
        printf("%d ",p->data);
        //printf("%d ",p->next->data);
        // 防止p指空报错
        if(p->next != NULL){
          p = p->next;
        }else{
          break;
        }
      }
    
      printf("
    ");
      // 测试指针能不能指回去
      p = p->prior;
      printf("%d ",p->data);
      printf("
    ");
    
      return 0;
    }

  • 相关阅读:
    useState回调函数
    Ahook
    我的创业和职业观点
    一个超级工业软件的能力在哪
    【542】Mac上面修改jupyter notebook默认打开页面
    【541】shapely 相关功能
    【540】时间戳数字转换为格式化时间
    【539】地球两点距离以及面积计算
    【538】二维数据实现随机采样
    新春首发!Spring Boot 2 个新版本...
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9396045.html
Copyright © 2020-2023  润新知