也是在笔试和面试的时候遇到的,当时也就光记得《数据结构》上非递归算法了,今天都写在这,对比着记记。
首先是递归算法,形参是两个链表第一个结点的指针。Node* mergAction(Node* head1,Node *head2) { Node *p=NULL; if(head1==NULL&&head2==NULL) return p; else if(head1==NULL) return head2; else if(head2==NULL) return head1; else { if(head1->data < head2->data) { p = head1; p->next = mergAction(head1->next,head2); } else { p = head2; p->next = mergAction(head1,head2->next); } return p; } } 然后是非递归的,严蔚敏《数据结构》有序链表合并算法的C++实现,其中pha,phb,phc都是指针的引用,注意这个是有头结点的哦。
这里给出完整的实现。MergeList为合并函数。其余部分也很简单,运行下就知道了。#include “stdafx.h” #include <malloc.h> typedef char DATA_TYPE; typedef struct node { DATA_TYPE data; struct node *next; }LIST_NODE; typedef LIST_NODE *plist; plist CreateList() { plist phead,p,r; DATA_TYPE ch; phead=(plist)malloc(sizeof(LIST_NODE)); r=p=phead; while ((ch=getchar())!=’/n’) { p=(plist)malloc(sizeof(LIST_NODE)); p->data=ch; r->next=p; r=p; } p->next=NULL; return phead; } void MergeList(plist &pha, plist &phb, plist &phc) { plist pa,pb,pc; pa=pha->next; pb=phb->next; pc=phc=pha; while(pa && pb) { if (pa->data<=pb->data) { pc->next=pa; pc=pa; pa=pa->next; } else { pc->next=pb; pc=pb; pb=pb->next; } } pc->next=pa ? pa : pb; free(phb); } void ShowList(plist phead) { plist p; p=phead->next; printf(“————————————————–/n”); while(p) { printf(“%c “,p->data); p=p->next; } printf(“/n”); } int _tmain(int argc, _TCHAR* argv[]) { plist pa,pb,pc; pc=NULL; pa=CreateList(); pb=CreateList(); MergeList(pa,pb,pc); ShowList(pc); return 0; } Over,收工,睡觉!