码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-12 23:33:18      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:blog   2014   for   io   代码   new   

#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

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

标签:blog   2014   for   io   代码   new   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!