單鏈表逆轉

​#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct Node *PtrToNode;

struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;

List Read(); /* 細節在此不表 */
void Print( List L ); /* 細節在此不表 */

List Reverse( List L );

int main()
{
    List L1, L2;
    L1 = Read();
    L2 = Reverse(L1);
    Print(L1);
    Print(L2);
    return 0;
}
void Print( List L ){
    List p = L->Next;
    while(p){
        printf("%d ",p->Data);
        p=p->Next;
    }
    printf("\n");
}
  List Read(){
      int n;
      scanf("%d",&n);
      List p;
      List head = (List)malloc(sizeof(struct Node));
      head->Next=NULL;
      p=head;
      
      for(int i=0;i<n;i++){
          List node = (List)malloc(sizeof(struct Node));
          scanf("%d",&node->Data);
          p->Next = node;
          p=p->Next;
      }
      p->Next = NULL; 
      return head;
  }  
    
  
        
   List Reverse(List head){
    if(head == NULL || head->Next == NULL){
     return head; 
    }
    List h = (List)malloc(sizeof(struct Node));
    List pre = NULL;
    List next;
    head = head->Next;
    while(head){
        
        
        next =head->Next;
        head->Next = pre;
        pre = head;
        head= next;
        
    }
    
    h->Next= pre;
    
  
    
   
    return h;
}​

 

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