链表反转


题目1518:反转链表
题目描述:

输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:

对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL
struct Node{
       int x ;
       Node* next ;
};

Node* make_list(int n){
      Node *head , *before , *now;
      if(n == 0)
        return NULL ;
      head = before = (Node *)malloc(sizeof(Node)) ;
      scanf("%d" , &head->x) ;
      head->next = NULL ;
      for(int i = 1 ; i < n ; i++){
           now = (Node *)malloc(sizeof(Node)) ;
           scanf("%d" , &now->x) ;
           now->next = NULL ;
           before->next = now ;
           before = now ;
      }
      return head ;
}

Node * reverse_list(Node *head){
     if(head == NULL)
        return NULL ;
     Node *reverse_head , * now  , *nownext ,*before;
     now = head ;
     before = NULL ;
     while(now != NULL){
         nownext = now->next ;
         if(nownext == NULL)
            reverse_head = now ;
         now->next = before ;
         before = now ;
         now = nownext ;
     }
     return reverse_head ;
}

void out_list(Node* head){
     if(head == NULL){
        puts("NULL") ;
        return ;
     }
     Node *now = head ;
     printf("%d" ,now->x) ;
     now = now->next ;
     while(now != NULL){
        printf(" %d" , now->x) ;
        now = now->next ;
     }
     puts("") ;
}


int main(){
    int n ;
    while(scanf("%d",&n)!=EOF){
         Node* head = make_list(n) ;
         //out_list(head) ;
         Node* re_head = reverse_list(head) ;
         out_list(re_head) ;
    }
    return 0 ;
}







你可能感兴趣的:(链表反转)