# 新手提问，非常简单，关于链表的反向输出

mm1543 2008-03-26 01:37:47

#include <iostream>
struct node
{
int data;
node* next;
};

void reverse(node*& head);

void main()
{
using namespace std;
node anode;
cin>>anode.data;
node* h=&anode;
node *pre;
for( int i=1; i<5; i++)
{
node anode2;
cin>>anode2.data;
node *n=&anode2;
if (i==1)
{
h->next=n;
}
else
{
pre->next =n;
}
pre=n;

}

reverse(h);
for (int j=0; j<5; j++)
{
cout<<(h+j)->data;
}
return ;
}

void reverse(node*& head)
{
node * pre, *bak, *now;
if (head==NULL)
return;
pre=head;
now=head;
bak=head->next;
while (bak!=NULL)
{
now=bak;
bak=now->next;
now->next=pre;
pre=now;
}
}
...全文
62 3 打赏 收藏 举报

3 条回复

mm1543 2008-03-26
• 打赏
• 举报

ryfdizuo 2008-03-26
• 打赏
• 举报

``````
//更改较大；
#include  <iostream>
struct node
{
int data;
node* next;
node():next(NULL)
{}
};

void reverse(node*& head);
void DeleteList(node* head);

void main()
{
using namespace std;

node* h=new node;
cin>>h->data;

node *pre;
for( int i=1; i <5; i++)
{
node*n = new node;
cin>>n->data;

if (i==1)
{
h->next=n;
pre=h->next;
}
else
{
pre->next=n;
pre=pre->next;
}
}
reverse(h);
node *p=h;
while (p)
{
cout<<p->data<<endl;
p = p->next;
}

DeleteList(h);
return ;
}

void reverse(node*& head)
{
node * pre, *bak, *now;
if (head==NULL)
return;
pre=head;
now=head;
bak=head->next;
while (bak!=NULL)
{
now=bak;
bak=now->next;
now->next=pre;
pre=now;
}
head->next=NULL;		//打断原来head节点和第二个节点之间的联系；
head = now;				//更新头节点；
}
void DeleteList(node* head)
{
node *p;
while (head)
{
p=head;
head=head->next;
delete p;
}
}``````
bargio_susie 2008-03-26
• 打赏
• 举报

``````#include  <iostream>
using namespace std;

struct node
{
int data;
node *next;
};

void reverse(node*& head);

void main()
{
node anode;
cin>>anode.data;

node *h = &anode;
node *pre = h;

for( int i=1; i <5; i++)
{
node *anode2 = new node;
cin>>anode2->data;
anode2->next = NULL;
node *n = anode2;

if (i == 1)
{
h->next = n;
}
else
{
pre->next = n;
}
pre = n;

}

reverse(h);
//	for (int j=0; j <5; j++)
//	{
//		cout << (h+j)->data;
//}
while (h != NULL)
{
cout << h->data << ' ';
h = h->next;
}

return;
}

void reverse(node*& head)
{
node *bak, *now;

if (head==NULL)
return;

now = head;
bak = head->next;
head->next = NULL;

while (bak != NULL)
{
now = bak->next;
bak->next = head;
head = bak;
bak = now;
}
}
``````

6.3w+

C++ 语言相关问题讨论，技术干货分享，前沿动态等
c++ 技术论坛（原bbs）

2008-03-26 01:37

1. 请不要发布与C++技术无关的贴子
2. 请不要发布与技术无关的招聘、广告的帖子
3. 请尽可能的描述清楚你的问题，如果涉及到代码请尽可能的格式化一下