[C++] 带头结点的单链表的就地逆置 →→→→→进入此内容的聊天室

来自 , 2019-10-21, 写在 C++, 查看 135 次.
URL http://www.code666.cn/view/5ec829de
  1. //库函数头文件包含
  2. #include<stdio.h>
  3. #include<malloc.h>
  4. #include<stdlib.h>
  5.  
  6. //函数状态码定义
  7. #define TRUE        1
  8. #define FALSE       0
  9. #define OK          1
  10. #define ERROR       0
  11. #define INFEASIBLE -1
  12. #define OVERFLOW   -2
  13.  
  14. typedef int  Status;
  15. typedef int  ElemType; //假设线性表中的元素均为整型
  16.  
  17. typedef struct LNode
  18. {
  19.     ElemType data;
  20.     struct LNode *next;
  21. }LNode,*LinkList;
  22.  
  23. Status ListCreate_L(LinkList &L,int n)
  24. {
  25.     LNode *rearPtr,*curPtr;   //一个尾指针,一个指向新节点的指针
  26.     L=(LNode*)malloc(sizeof (LNode));
  27.     if(!L)exit(OVERFLOW);
  28.     L->next=NULL;               //先建立一个带头结点的单链表
  29.     rearPtr=L;  //初始时头结点为尾节点,rearPtr指向尾巴节点
  30.     for (int i=1;i<=n;i++){  //每次循环都开辟一个新节点,并把新节点拼到尾节点后
  31.         curPtr=(LNode*)malloc(sizeof(LNode));//生成新结点
  32.         if(!curPtr)exit(OVERFLOW);
  33.         scanf("%d",&curPtr->data);//输入元素值
  34.         curPtr->next=NULL;  //最后一个节点的next赋空
  35.         rearPtr->next=curPtr;
  36.         rearPtr=curPtr;
  37.     }
  38.     return OK;
  39. }
  40. void ListReverse_L(LinkList &L)
  41. {
  42.     LNode *p,*a;
  43.     a=L->next;
  44.     while(a->next!=NULL)
  45.     {
  46.         p=a->next;
  47.         a->next=p->next;
  48.         p->next=L->next;
  49.         L->next=p;
  50.     }
  51. }
  52. void ListPrint_L(LinkList &L){
  53. //输出单链表
  54.     LNode *p=L->next;  //p指向第一个元素结点
  55.     while(p!=NULL)
  56.     {
  57.           if(p->next!=NULL)
  58.                printf("%d ",p->data);
  59.           else
  60.                printf("%d",p->data);
  61.           p=p->next;
  62.     }
  63. }
  64. int main()
  65. {
  66.     LinkList L;
  67.     int n;
  68.     scanf("%d",&n);
  69.     if(ListCreate_L(L,n)!= OK) {
  70.           printf("表创建失败!!!\n");
  71.           return -1;
  72.     }
  73.     ListReverse_L(L);
  74.     ListPrint_L(L);
  75.     return 0;
  76. }

回复 "带头结点的单链表的就地逆置"

这儿你可以回复上面这条便签

captcha