链表逆序(C++)

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define TRUE        1
#define FALSE       0
#define OK          1
#define ERROR       0
#define INFEASIBLE -1
#define OVERFLOW   -2
#define  NULL       0    //代表空指针
typedef int  status;

typedef int elemtype;
typedef struct LNode{
    elemtype data;          //数据域
    struct LNode * next;  //指针域
}LNode,*linklist;
status listcreate(linklist &L,elemtype n)//创建
{
 LNode *p1,*p2;
 L=(linklist)malloc(sizeof(LNode));
 L->next=NULL;
 p1=L;//L始终指向头结点,L不能指向其他节点(不能后移),必须另外定义指针P1,P1开始指向L,之后P1可以后移
  for(int i=0;i<n;i++)
 {
  p2=(LNode*)malloc(sizeof(LNode));
   if(!p2) return ERROR;
  printf("input data :");
  scanf("%d", &p2->data );//别忘&
  p1->next=p2;//L->next=p2是错误的
  p1=p2;//指针后移
  p2->next=NULL;
 }
 return OK;
}
status listinsert(linklist &L,int i,elemtype e)//插入
{
 LNode *p=L,*q;
 int j=0;
    while(p && j<i-1)
 {p=p->next;j++;}
 q=(LNode *)malloc(sizeof(LNode));
 if(!q) return ERROR;
 q->data=e;
 q->next=p->next;
 p->next=q;
 return OK;
}
status listreserve(linklist &L)//逆序
{
 LNode *h=L->next,*p1=NULL,*p2=NULL;
 while(h)
 {
     p2=h->next;
     h->next=p1;
     p1=h;
     h=p2;
 }
 L->next=p1;//注意是从L后的第一个节点开始,所以不是L=P1
 return OK;
}
status listprint(linklist L)
{
 LNode *p;
 p=L->next;//注意这里P指向链表的第一个节点,p=L;p将指向L的头结点,下面输出应为p->next->data
 while(p)
 {
  printf(" %d ",p->data);
  p=p->next;
 }
 printf("\n");
 return OK;
}
void main()
{
 linklist L;int n=3;
 listcreate(L,n);
 printf("创建链表为:\n");
 listprint(L);

 listinsert(L,2,3);
 listinsert(L,1,9);
    printf("插入元素后链表为:\n");
     listprint(L);

 listreserve(L);
    printf("逆序后链表为:\n");
 listprint(L);

}

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