您的位置:首页 > 其它

题目1518:反转链表

2014-11-19 21:15 239 查看
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;
struct Node
{
int num;
Node * next ;
};

void print(Node * head)
{
int flag=1;
while(head->next)
{
printf("%d ",head->num);
head=head->next;
}
printf("%d",head->num);
}

int main()
{
int n;
Node * head=NULL;
Node * tail=head;

while(~scanf("%d",&n))
{
if(n==0) printf("NULL\n");
else
{
int t;
Node * temp=(Node *)malloc(sizeof(Node ));
temp->next=NULL;
head=temp;
tail=head;
while(n--)
{
scanf("%d",&t);
temp=(Node *)malloc(sizeof(Node ));
temp->num=t;
temp->next=head->next;
head->next=temp;
}
print(head->next);
printf("\n");
}
}
return 0;
}

/**************************************************************
Problem: 1518
User: 萧然677
Language: C++
Result: Accepted
Time:150 ms
Memory:2972 kb
****************************************************************/


逆序输出链表,开始使用递归但发现最后输出时有格式错误,最后的那个空格不知道怎么处理(有大神知道方法可以告诉我哈)。然后改用头插法生成单链表,当建立好链表后此时的链表已经是逆序的。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: