PAT 单链表逆转

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. typedef int ElementType;  
  5. typedef struct Node *PtrToNode;  
  6. struct Node {  
  7.     ElementType Data;  
  8.     PtrToNode   Next;  
  9. };  
  10. typedef PtrToNode List;  
  11.   
  12. List Read(); /* 细节在此不表 */  
  13. void Print( List L ); /* 细节在此不表 */  
  14.   
  15. List Reverse( List L );  
  16.   
  17. int main()  
  18. {  
  19.     List L1, L2;  
  20.     L1 = Read();  
  21.     L2 = Reverse(L1);  
  22.     Print(L1);  
  23.     Print(L2);  
  24.     return 0;  
  25. }  
  26. List Read()  
  27. {  
  28.     PtrToNode head=NULL;  
  29.     PtrToNode list=NULL;  
  30.     int len;  
  31.     scanf("%d",&len);  
  32.     if(len==0)  
  33.     return NULL;  
  34.     int num;  
  35.     scanf("%d",&num);  
  36.     head=(PtrToNode)malloc(sizeof(struct Node));  
  37.     head->Data=num;  
  38.     head->Next=NULL;  
  39.     list=head;  
  40.     len--;  
  41.     while(len)  
  42.     {  
  43.      PtrToNode node=(PtrToNode)malloc(sizeof(struct Node));  
  44.         scanf("%d",&num);  
  45.     node->Data=num;  
  46.     node->Next=NULL;  
  47.     list->Next=node;  
  48.     list=node;  
  49.         len--;  
  50.     }  
  51.     return head;      
  52. }  
  53. void Print( List L )  
  54. {  
  55.     if(L==NULL)  
  56.     return ;  
  57.     while(L!=NULL)  
  58.     {  
  59.         printf("%d ",L->Data);  
  60.         L=L->Next;  
  61.     }  
  62.     putchar('\n');  
  63. }  
  64. List Reverse( List L )  
  65. {  
  66.     if(L==NULL)  
  67.     return NULL;  
  68.     PtrToNode l1=NULL;  
  69. //  PtrToNode l3=L;  
  70.     PtrToNode l2=NULL;  
  71.     while(L!=NULL)  
  72.     {  
  73.         l1=L->Next;  
  74.         L->Next=l2;  
  75.         l2=L;  
  76.         L=l1;  
  77.     }  
  78.     return l2;  

笔记:typedef struct Node * PtrToNode 
      struct Node *  =   PtrToNode 
    PtrToNode  List 相当于定义了一个 struct Node 类型的指针




 1.对List read()解析
先要定义一个结构变量   赋值为NULL;
开辟一个结构空间 。
然后输入数据长度,判断是否为0   ,是则返回NULL
不是则继续输入数据,然后数据弄到结构里面去,记得Next为NULL;
那么要判断了如果有大于等于一个元素,就要在list里面继续添加下去,怎么做呢?
用循环来做啊
while(len)     在 里面开辟一个 PtrToNode 类型的变量 node  那么这个变量就带有  num 和 NULL
每次输入一个数 在把list 指向node 即可一个链表形成了;
OK,going on。
在重新写一个看看
2.对Print函数进行解析
你要输出  首先要看这个它有没有空?没有才可以输出的。
if(L==NULL)  
3.Reverse 函数  首先判断空不  要写  if (L==NULL)?
不空在进行下面的步骤。
设置一个临时储存的函数和一个储存逆反链表的链表。
现在coding


4.写一个完整的试一试;

猜你喜欢

转载自blog.csdn.net/qq_39429288/article/details/78449657