首页 > 其他 > 详细

C实现头插法和尾插法来构建双向非循环链表(带头结点尾结点)

时间:2016-03-04 11:48:07      阅读:303      评论:0      收藏:0      [点我收藏+]

     双向链表中如果有了头结点和尾结点,对于头插法和尾插法就显得非常方便。这样在尾部插入一个元素也就不用去遍历链表了。个人建议使用这种链表来处理问题。代码上传至  https://github.com/chenyufeng1991/HeadInsertAndTailInsert_DoubleList_HeadList

核心代码如下:

//创建带头结点和尾结点的双向非循环链表(头插法)
void HeadInsertCreateList(Node *pHead,Node *pTail){

    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->prior = NULL;
    pInsert->next = NULL;

    scanf("%d",&(pInsert->element));
    while (pInsert->element > 0) {

        pHead->next->prior = pInsert;
        pInsert->next = pHead->next;
        pInsert->prior = pHead;
        pHead->next = pInsert;

        pInsert = (Node *)malloc(sizeof(Node));
        memset(pInsert, 0, sizeof(Node));
        pInsert->prior = NULL;
        pInsert->next = NULL;

        scanf("%d",&(pInsert->element));
    }

    printf("%s函数执行完成,头插法建立带头节点和尾结点的双向非循环链表创建成功\n",__FUNCTION__);
}

//创建带头结点和尾结点的双向非循环链表(尾插法)
void TailInsertCreateList(Node *pHead,Node *pTail){

    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->prior = NULL;
    pInsert->next = NULL;

    scanf("%d",&(pInsert->element));
    while (pInsert->element > 0) {

        pTail->prior->next = pInsert;
        pInsert->prior = pTail->prior;
        pInsert->next = pTail;
        pTail->prior = pInsert;

        pInsert = (Node *)malloc(sizeof(Node));
        memset(pInsert, 0, sizeof(Node));
        pInsert->prior = NULL;
        pInsert->next = NULL;

        scanf("%d",&(pInsert->element));
    }

    printf("%s函数执行完成,尾插法建立带头节点和尾结点的双向非循环链表创建成功\n",__FUNCTION__);
}

测试代码如下:

int main(int argc, const char * argv[]) {

    Node *pHead;//头结点
    Node *pTail;//尾结点

    InitialList(&pHead, &pTail);

    HeadInsertCreateList(pHead, pTail);
    PrintList(pHead, pTail);
    TailInsertCreateList(pHead, pTail);
    PrintList(pHead, pTail);


    return 0;
}


C实现头插法和尾插法来构建双向非循环链表(带头结点尾结点)

原文:http://blog.csdn.net/chenyufeng1991/article/details/50800779

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!