65,210
社区成员
发帖
与我相关
我的任务
分享
在你原创的基础上改进一下:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct itm
{
int num;
itm *next;
};
itm *creat()
{
itm *p,*q,*head;
head=NULL;
q=NULL;
int i;
cin>>i;
while(i!=NULL)
{
p=new itm; //必须分配空间
p->num=i;
if(head==NULL)
{
head=p;
}
else
q->next=p;
q=p;
cin>>i;
}
q->next=NULL;
return head;
}
itm *listnode(itm *&head)
{
itm* p, *q,*r;
p = head;
q = p->next;
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = NULL;
return p;
}
void print(itm *head)
{
itm *q;
q=head;
while(q!=NULL) //这个地方不应该是q->next
{
cout <<q->num;
q=q->next;
}
}
int main(int argc, char *argv[])
{
itm *p,*q;
p=creat();
q=listnode(p);
print(q);
system("PAUSE");
return 0;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
struct itm
{
int num;
itm *next;
};
itm *creat()
{
itm *p,*q,*head;
head=new itm;//必须分配空间
head=NULL;
q=NULL;
int i;
while(cin>>i)
{
p=new itm; //必须分配空间
p->num=i;
if(head==NULL)
{
head=p;
q=head;//应该把q指向head
}
else
q->next=p;
q=p;
}
q->next=NULL;
return head;
}
itm *listnode(itm *&head)
{
itm* p, *q,*r;
p = head;
q = p->next;
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = NULL;
return p;
}
void print(itm *head)
{
itm *q;
q=head;
while(q!=NULL) //这个地方不应该是q->next
{
cout <<q->num;
q=q->next;
}
}
int main(int argc, char *argv[])
{
itm *p,*q;
p=creat();
q=listnode(p);
print(q);
system("PAUSE");
return 0;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
struct itm
{
int num;
itm *next;
};
itm *creat()
{
itm *p,*q,*head;
head=NULL;
q=NULL;
int i;
cin>>i;
while(i!=NULL)
{
p=new itm;
p->num=i;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
cin>>i;
}
q->next=NULL;
return head;
}
itm *listnode(itm *&head)
{
itm *p,*q,*r;
p=head;
q=p->next;
r=NULL;
while(q!=NULL)
{
p->next=r;
p=p->next;
r=p;
delete p;
q=q->next;
}
return q;
}
itm* subrev(itm* subhead, itm*& new_head)
{
if (subhead->next == NULL)
{
new_head = subhead;
return subhead;
}
subrev(subhead->next, new_head)->next = subhead;
return subhead;
}
itm* reverse(itm* head)
{
itm* new_head = NULL;
if (head == NULL)
return NULL;
subrev(head, new_head)->next = NULL;
return new_head;
}
void print(itm *head)
{
itm *q = head;
while (q)
{
cout<<q->num<<" ";
q = q->next;
}
cout<<endl;
}
int main(int argc, char *argv[])
{
itm *p,*q;
p=creat();
//q=listnode(p);
q = reverse(p);
cout<<endl;
print(q);
system("PAUSE");
return 0;
}
-----------
测试
1 2 3 4 5 6 7 8 9 0
9 8 7 6 5 4 3 2 1
请按任意键继续. . .
itm *listnode(itm *&head)
{
itm* p, *q;
itm* old_qnext;
p = head;
q = p->next;
while(p && q)
{
old_qnext = q->next;
q->next = p;
p = q;
q = old_qnext;
}
head->next = NULL;
return p;
}