C-双向链接的创建与遍历(15)

来源:互联网 发布:域名历史记录查询 编辑:程序博客网 时间:2024/05/01 07:43
#include <stdio.h>#include <stdlib.h>//声明一个创建链表函数,并返回头结点//利用头结点进行对链表的遍历struct Node *create_Linked(); //遍历链表函数void foreach_forward(struct Node *);void foreach_reverse(struct Node *);struct Node *pHeader=NULL;struct Node *pFooter=NULL;//定义一个结构体struct Node{int val;struct Node * pNext;struct Node * pPrevious;};int main(int argc,char *argv[]){pFooter=create_Linked();printf("-------正向遍历--------\n");foreach_forward(pHeader);printf("-------反向遍历--------\n");foreach_reverse(pFooter);return 0;}//创建一个双向链表struct Node *create_Linked(){struct Node *mLast=NULL;struct Node *mCurrent=NULL;struct Node *mPrevious=NULL;int length=5;int i = 0;for (; i < length; i++){mCurrent=(struct Node *)malloc(sizeof(struct Node));mCurrent->val=i;mCurrent->pNext=NULL;mCurrent->pPrevious=NULL;if (mPrevious!=NULL){mCurrent->pPrevious=mPrevious;mPrevious->pNext=mCurrent;}if (mCurrent->pPrevious==NULL){pHeader=mCurrent;}if (mCurrent->pNext==NULL){mLast=mCurrent;}mPrevious=mCurrent;}return mLast;}void foreach_forward(struct Node *pHeader){struct Node *temp=pHeader;int j=0;while (temp!=NULL){printf("第%d个地址的内容是%d\n",j++,temp->val);temp=temp->pNext;}}void foreach_reverse(struct Node *pFooter){struct Node *temp=pFooter;int j=0;while (temp!=NULL){printf("第%d个地址的内容是%d\n",j++,temp->val);temp=temp->pPrevious;}}

0 0