双链表和单链表性质相似只是在多加了一个前指针
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("申请空间失败\n"); exit(-1); } L = Head; L->next = NULL; for(i=0;i<5;i++){ LNew = (Node *)malloc(sizeof(Node)); if(LNew == NULL){ printf("申请空间失败\n"); 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("\n"); // 测试指针能不能指回去 p = p->prior; printf("%d ",p->data); printf("\n"); return 0; }