zoukankan      html  css  js  c++  java
  • 将两个有序链表和为另外一个链表,并保证有序

    直接递归

    代码:

    #include <iostream>
    #include <stack>
    using namespace std;
    
     typedef struct listNode{
    	int key;
    	struct	listNode *pNext;
     } * pNode,Node;
    
    void createNode(pNode &pHead){
    		bool isFirst=true;
    		int temp;
    		scanf("%d",&temp);
    		pNode p=pHead,q;
    		while(temp!=0){
    			q=(pNode)malloc(sizeof(Node));
    			q->key=temp;
    			q->pNext=NULL;
    			if(isFirst){
    				p=pHead=q;
    				isFirst=false;
    			}else{
    				p->pNext=q;
    				p=q;
    			}
    
    			scanf("%d",&temp);
    		}
    		cout<<"原链表是:"<<endl;
    		p=pHead;
    		while(p){
    			cout<<p->key<<" ";
    			p=p->pNext;
    		}
    }
    void print(const pNode merge){
    	pNode p=merge;
    	while(p){
    		cout<<p->key<<" ";
    		p=p->pNext;
    	}
    }
    pNode merge(const pNode pHead1,const pNode pHead2){
    	
    	if(pHead1==NULL)
    		return pHead2;
    	else if(pHead2==NULL)
    		return pHead1;
    	pNode pMerge=NULL;
    	if(pHead1->key > pHead2->key){
    		pMerge = pHead2;	
        	pMerge->pNext = merge(pHead1,pHead2->pNext);
    	}else{
    		pMerge=pHead1;	
    		pMerge->pNext=merge(pHead1->pNext,pHead2);
    	}
    	
    	return pMerge;
    }
    void printListReverse(const pNode pHead){
    	if(pHead==NULL)
    		return;
    	printListReverse(pHead->pNext);
    	cout<<pHead->key;
    
    }
    
    int main(){
    	pNode pHead1=NULL;
    	pNode pHead2=NULL;
    
    	createNode(pHead1);
    	createNode(pHead2);
    	pNode merge1 = merge(pHead1,pHead2);
    	print(merge1);
    	return 0;
    
    }

    执行结果:


  • 相关阅读:
    [小知识]如何查看IIS6应用程序池所对应的进程ID
    继续向大家汇报服务器情况
    CNBlogs DotText 1.0 Beta 2 重要更新
    垃圾广告记录
    Firefox 11正式发布
    Firefox 10正式发布
    Firefox 6 正式发布
    Firefox 5 正式发布
    Firefox 9正式发布
    Firefox 8正式发布
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/7234529.html
Copyright © 2011-2022 走看看