单链表操作续
#include<iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef struct ListTableCell
{
char mdata[20];
struct ListTableCell *next;
}LtCell;
LtCell *LTProductor(int ListLength){
LtCell *headp,*pre,*nowptr;
if ((headp= (LtCell*)malloc(sizeof(LtCell)))==NULL) //这是内存检测的一步,很重要
{
cout<<"Some Memory is shortage!"<<endl;
exit(0);
}
headp->next=NULL;
headp->mdata[0]='/0';
pre=headp;
for (int i=0;i<ListLength;i++) //用nowptr生成新的listcell,然后通过pre完成对链表的连接
{
if ((nowptr=(LtCell*)malloc(sizeof(LtCell)))==NULL)
{
cout<<"Memory is not enough for strage of new data"<<endl;
exit(0);
}
pre->next=nowptr; //上一级连到下一级,注意第一次要返回的指针是nowptr,不是指向它的headp(pre)
cout<<"Please input Data for list:"<<endl;
//scanf("%s",nowptr->mdata);
cin>>nowptr->mdata; //直接将输入数据地址赋给当前listcell的数据项
pre=nowptr; //将上一级变成下一级,继续上面过程
}
headp=headp->next; //链表建立完了以后记得把
pre->next=NULL;
printf("head data is:%s\n",headp->mdata);
return (headp);
}
/********************************************Reverse List*********************************************************************/
LtCell* ListReverse(LtCell *head){
if (head==NULL || head->next==NULL) //先判断head是否为空,或就一个元素,是则返回head
{
return (head);
}
LtCell *p1,*p2,*p3; //定义三个指针指向邻接list元素
p1=head; //将list头指针给它,并可让p1向后移动,以2为单位反转
p2=p1->next;
while (p2) //p1的下个元素是否存在,存在,则需将p2和p1反转
{
p3=p2->next; //注意:若此时p2是最后一个元素,则要注意此时的p3是错误指针;所以下一步需要将p2->next赋值
p2->next=p1; //将它反转指向前一个元素
p1=p2; //完成反转后,需要将p1,p2向后移动,继续反转过程
p2=p3;
}
head->next=NULL; //此时head为原序列第一个元素,它有一部分指向第二元素,需将下个元素设为NULL
head=p1;
return (head);
}
/******************************************Print List****************************************************************/
void PrintList(LtCell *h){
LtCell *p;
p=h;
if (p==NULL)
{
cout<<"No list to print!"<<endl;
}
while(p){
cout<<"List data is:"<<p->mdata<<endl;
p=p->next;
}
}
/*****************************************************************************************************************/
int main(){
LtCell *mListHead=NULL,*rhead;
int listnm;
cout<<"Input the length of List:"<<endl;
cin>>listnm;
mListHead=LTProductor(listnm);
rhead=ListReverse(mListHead);
PrintList(rhead);
system("pause");
return 0;
}

浙公网安备 33010602011771号