首页 > 其他 > 详细

递归逆转链表和递归合并有序链表的代码

时间:2014-07-12 23:33:36      阅读:337      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>

struct node
{
    int val;
    struct node *pNext;
};


struct node *gen()
{
    struct node *pHead = NULL;

    for(int i = 10; i > 0; i--){
        struct node * p = malloc(sizeof(struct node));
        p -> val = i;
        p -> pNext = pHead;
        pHead = p;
    }   
    return pHead;
}

void display(struct node *pHead) 
{
    while( pHead != NULL)
    {   
        printf("%d ", pHead->val);
        pHead = pHead->pNext;
    }   
    printf("\n");
}

struct node * reverse(struct node *pHead)
{
    if (pHead == NULL || pHead -> pNext == NULL)
    {   
        return pHead;
    }   
    struct node *p = pHead -> pNext;
    struct node *pNewHead =  reverse(p);
    p -> pNext = pHead;
    pHead ->pNext = NULL;
    return pNewHead;
}
struct node * merge(struct node *pHeadA, struct node *pHeadB)
{
    if(pHeadA == NULL )
        return pHeadB;
    if(pHeadB == NULL )
        return pHeadA;
    if(pHeadA -> val < pHeadB -> val)
    {
        pHeadA -> pNext = merge(pHeadA -> pNext, pHeadB);
        return pHeadA;
    }
    else
    {
        pHeadB -> pNext = merge(pHeadA, pHeadB -> pNext);
        return pHeadB;
    }
}

int main()
{
    struct node *pHead = gen();
    display(pHead);
    struct node *pHeadB = gen();
    pHead = merge(pHead, pHeadB),
    display(pHead);
    pHead = reverse(pHead);
    display(pHead);
}

递归逆转链表和递归合并有序链表的代码,布布扣,bubuko.com

递归逆转链表和递归合并有序链表的代码

原文:http://blog.csdn.net/moxiaopeng/article/details/37695797

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