您的位置:首页 > 其它

20140720 链表反转 、合并、二叉树镜像

2014-07-20 14:22 791 查看
1、链表的反转

#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct ListNode
{
int data;
struct ListNode * Next;
}ListNode;

ListNode *ReverseList(ListNode *pHead)
{
ListNode *PReverseHead=NULL;
ListNode *pBefore=NULL;
ListNode *pAfter=NULL;
ListNode *pNode=pHead;
while(pNode!=NULL)
{
pAfter=pNode->Next;

if(pNode->Next==NULL)
{PReverseHead=pNode;}
pNode->Next=pBefore;
pBefore=pNode;
pNode=pAfter;
}
return PReverseHead;
}

ListNode *CreateList()
{
int x=0;
cout<<"input data:";  cin>>x;
if(x==0)
return NULL;
ListNode *pHead=(ListNode *)malloc(sizeof(ListNode));
pHead->data=x;
pHead->Next=NULL;
ListNode *rear=pHead;
cout<<"input data:";    cin>>x;
while(x!=0)
{
ListNode *p=(ListNode *)malloc(sizeof(ListNode));
p->data=x;
p->Next=NULL;
rear->Next=p;
rear=p;
cout<<"input data:";
cin>>x;
}
return pHead;
}

void PrintList(ListNode *pHead)
{
ListNode *p=pHead;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->Next;
}
}
void main()
{
ListNode *pHead=CreateList();
PrintList(pHead);
ListNode *pReverseHead=ReverseList(pHead);

PrintList(pReverseHead);
}


2、合并链表

#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct ListNode
{
int data;
struct ListNode * Next;
}ListNode;

ListNode *MergeList(ListNode *pHead1,ListNode *pHead2)
{
if(pHead2==NULL)
return pHead1;
if(pHead1==NULL)
return pHead2;
ListNode *pMergeHead=NULL;
if(pHead1->data<pHead2->data)
{
pMergeHead=pHead1;
pHead1->Next=MergeList(pHead1->Next,pHead2);
}
else
{
pMergeHead=pHead2;
pHead2->Next=MergeList(pHead1,pHead2->Next);
}
return pMergeHead;
}

ListNode *CreateList()
{
int x=0;
cout<<"input data:";  cin>>x;
if(x==0)
return NULL;
ListNode *pHead=(ListNode *)malloc(sizeof(ListNode));
pHead->data=x;
pHead->Next=NULL;
ListNode *rear=pHead;
cout<<"input data:";    cin>>x;
while(x!=0)
{
ListNode *p=(ListNode *)malloc(sizeof(ListNode));
p->data=x;
p->Next=NULL;
rear->Next=p;
rear=p;
cout<<"input data:";
cin>>x;
}
return pHead;
}

void PrintList(ListNode *pHead)
{
ListNode *p=pHead;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->Next;
}
}
void main()
{
ListNode *pHead1=CreateList();
ListNode *pHead2=CreateList();
ListNode *pMergeNode=MergeList(pHead1,pHead2);
PrintList(pMergeNode);
}


3、两颗二叉树,查找是否存在子结构

4、写代码之前先讲思路,举例子和画图是很好的方法-田超(微软)

5、无法解析的外部符号原因是没有包含相应的.lib文件





6、二叉树的镜像
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: