首页 > 代码库 > 递归逆转链表和递归合并有序链表的代码
递归逆转链表和递归合并有序链表的代码
#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); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。