題目1518:反轉鏈表

#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
****************************************************************/

 

逆序輸出鏈表,開始使用遞歸但發現最後輸出時有格式錯誤,最後的那個空格不知道怎麼處理(有大神知道方法可以告訴我哈)。然後改用頭插法生成單鏈表,當建立好鏈表後此時的鏈表已經是逆序的。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章