// ConvertList.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
struct ListNode
{
int Element;
ListNode *Next;
};
typedef ListNode*pListNode;
typedef pListNode List;
List CreatList()
{
pListNode p ,q,head;
head=(ListNode *)malloc(sizeof(struct ListNode));
if(head==NULL)
{
cerr<<"out of space"<<endl;
return NULL;
}
head->Next=NULL;
int a;
int i=0;
cout<<"please input the data(input -1,quit):"<<endl;
while(1)
{
cin>>a;
if(a==-1)
break;
p=(ListNode*)malloc(sizeof(ListNode));
p->Element=a;
p->Next=NULL;
i++;
if(i==1)
head->Next=p;
else
q->Next=p;
q=p;
}
return head;
}
void PrintList(List head)
{
pListNode p=head->Next;
if(p==NULL)
{
cerr<<"empty List"<<endl;
exit(0);
}
while(p!=NULL)
{
cout<<p->Element<<endl;
p=p->Next;
}
}
////方法一
//List ReverseList(List head)
//{
// pListNode p,q,r;
// p=head->Next;
// if(p==NULL)
// {
// cerr<<"empty List"<<endl;
// return head;
// }
// q=p->Next;
// if(q==NULL)
// return head;
// r=q->Next;
// q->Next=p;
// p->Next=NULL;
// while (r!=NULL)
// {
// p=q;
// q=r;
// r=q->Next;
// q->Next=p;
// }
// head->Next=q;
// return head;
//}
//方法二
List ReverseList(List mylist)
{
pListNode p,q;
p=mylist->Next;
if(p==NULL)
{
cerr<<"out of space"<<endl;
return mylist;
}
int i=0;
while(p!=NULL)
{
q=p;
p=p->Next;
q->Next=NULL; //注意此处赋NULL
i++;
if(i==1)
mylist->Next=q;
else
{
q->Next=mylist->Next;
mylist->Next=q;
}
}
return mylist;
}
int _tmain(int argc, _TCHAR* argv[])
{
List myList=CreatList();
PrintList(myList);
ReverseList(myList);
PrintList(myList);
return 0;
}
反转单链表
最新推荐文章于 2025-08-08 17:00:29 发布