标签:双向链表
引言:
单链表存在一个问题,当我们想要访问某个结点的前一个结点时,要从头结点开始访问。显然这样的操作是令人烦躁的。为此,双向链表出现,它比单链表多出了一个指针域,指向前一个结点。这样,对于双向链表,就可以方便的从后向前遍历链表了。但多出的问题是对于插入和删除结点的开销要增加一倍。
分析描述:
双向链表存储结构图为:,用结构体表示如下:
typedef int ElemType; typedef struct LNode{ ElemType data; struct LNode *prior; struct LNode *next; }LNode, *PLNode;
PLNode InitDList(void) { PLNode HeadLNode = (PLNode)malloc(sizeof(LNode)); if(HeadLNode == NULL){ printf("malloc memory fail.\n"); return NULL; } HeadLNode->prior = HeadLNode->next = HeadLNode; return HeadLNode; }
PLNode CreateDList(PLNode PHeadNode) { PLNode TmpLNode = (PLNode)malloc(sizeof(LNode)); if(TmpLNode == NULL){ printf("malloc memory fail.\n"); return PHeadNode; } TmpLNode->next = NULL; while(scanf("%d", &TmpLNode->data) != 0){ TmpLNode->next = PHeadNode->next; TmpLNode->prior = PHeadNode; PHeadNode->next = TmpLNode; if(TmpLNode->next != NULL)//此处的判断是针对空链表的操作,如果是空链表,下面的语句就不做。 TmpLNode->next->prior = TmpLNode; TmpLNode = (PLNode)malloc(sizeof(LNode)); if(TmpLNode == NULL){ return PHeadNode; } } free(TmpLNode); return PHeadNode; }
void TraverseDList(PLNode PHeadNode) { PLNode TmpLNode = PHeadNode; if(PHeadNode == NULL) { printf("input element faulse.\n"); return ; } while(TmpLNode->next != NULL){ printf("%d ", TmpLNode->next->data); TmpLNode = TmpLNode->next; } putchar('\n'); }
int ListLength(PLNode PHeadNode) { int count = 0; while(PHeadNode->next != NULL){ count++; PHeadNode = PHeadNode->next; } return count; }
PLNode InsertDList(PLNode PHeadNode, ElemType data, int Index) { int index = 0; PLNode TmpLNode = PHeadNode; if(PHeadNode == NULL || Index < 0 || Index > ListLength(PHeadNode) + 1){ printf("input element faulse.\n"); return NULL; } for(index = 1; index < Index; index++){ TmpLNode = TmpLNode->next; } PLNode Tmp = (PLNode)malloc(sizeof(LNode)); if(Tmp == NULL){ printf("malloc memory faluse.\n"); return PHeadNode; } Tmp->data = data; Tmp->next = TmpLNode->next; Tmp->prior = TmpLNode->prior; TmpLNode->next = Tmp; TmpLNode->prior = Tmp; return PHeadNode; }
PLNode DeleteList(PLNode PHeadNode, int Index) { int index; PLNode TmpNode = PHeadNode; if(PHeadNode == NULL || Index < 0 || Index > ListLength(PHeadNode)){ printf("input element faulse.\n"); return NULL; } for(index = 0; index < Index; index++){ TmpNode = TmpNode->next; } TmpNode->prior->next = TmpNode->next; if(TmpNode->next != NULL) TmpNode->next->prior = TmpNode->prior; free(TmpNode); return PHeadNode; }
PLNode DeleteList(PLNode PHeadNode, int Index) { int index; PLNode TmpNode = PHeadNode; if(PHeadNode == NULL || Index <= 0 || Index > ListLength(PHeadNode)){ printf("input element faulse.\n"); return NULL; } for(index = 0; index < Index; index++){ TmpNode = TmpNode->next; } TmpNode->prior->next = TmpNode->next; TmpNode->next->prior = TmpNode->prior; free(TmpNode); return PHeadNode; }
标签:双向链表
原文地址:http://blog.csdn.net/to_be_it_1/article/details/37570681