【练习】单链表反转,合并

//链表反转http://www.2cto.com/kf/201110/106607.html
//链表合并
#include <iostream>
using namespace std;

struct LinkList
{
	int value;
	LinkList* next;
};

void CreatLinkList(LinkList* &head)
{
	int n;
	if (!head)
	{
		cout<<"input nodes"<<endl;
		cin>>n;
		head=new LinkList;
		head->next=NULL;
		head->value=n;
	} 
		LinkList* prev=head;
		while (n!=-1)
		{
			cin>>n;
			if (n==-1)
			{
				break;
			}
			LinkList* pcurrent=new LinkList;
			pcurrent->value=n;
			prev->next=pcurrent;
			pcurrent->next=NULL;
			prev=pcurrent;
			
		}
	

}

void PrintLinkList(LinkList* head)
{
	if (head==NULL)
	{
		return;
	}
	while(head!=NULL)
	{
		cout<<head->value<<" ";
		head=head->next;
	}
	cout<<endl;
}


void ReverseLinkList(LinkList* &head)
{
	if (!head||!head->next)
	{
		return;
	}
	LinkList *p=head;
	LinkList *q=head->next;
	head->next=NULL;
	while (q)
	{
		LinkList *r=q->next;
		q->next=p;
		p=q;
		q=r;
	}
	head=p;
}

LinkList* CombineLinkList(LinkList* head1,LinkList* head2)
{

	LinkList* newhead=head1;
	if (!head1||!head2)
	{
		return NULL;
	}
	while(head1!=NULL)
	{
		if (head1->next==NULL)
		{
		 break;
		}
		head1=head1->next;
	}
	head1->next=head2;
	return newhead;

}

int main()
{
	LinkList *head=NULL;
	LinkList *head2=NULL;
	CreatLinkList(head);
	cout<<"list 1"<<endl;
	PrintLinkList(head);

	ReverseLinkList(head);
	cout<<"after reverse"<<endl;
	PrintLinkList(head);

	CreatLinkList(head2);
	cout<<"list 1"<<endl;
	PrintLinkList(head);
	cout<<"list 2"<<endl;
	PrintLinkList(head2);
	LinkList *newList=CombineLinkList(head,head2);
	cout<<"after combine linklist"<<endl;
	PrintLinkList(newList);

	return 0;
}

  

posted @ 2011-11-22 14:20  refazy  阅读(258)  评论(0编辑  收藏  举报