带头节点的单链表逆置

#include 


#include 
#include 

using namespace std;

//带头指针的单链表

typedef  struct  LNode{
    int data;
    struct LNode *next;

}LNode, *LinkList;

bool InitList(LinkList &L){
    L = (LNode *) malloc(sizeof(LNode));
    if(L== NULL){
        return false;  //内存不足分配失败
    }
    L->next =NULL;
    return true;
}
bool empty(LinkList &L){
    return  (L->next==NULL);
}

LinkList List_headInsert(LinkList &L){

    LNode *s ;
    L->next =NULL;


    int x;
    scanf("%d",&x);
    while(x!=9999){
        s = (LNode *)malloc(sizeof(LNode));
        s->data = x;
        s->next = L->next;
        L->next = s;
        scanf("%d",&x);

    }

    return L;


}

LinkList reverseList(LinkList &L){

    LNode *pre =L->next;

    L->next = NULL;

    while(pre!=NULL){

        LNode *s=(LNode *)malloc(sizeof(LNode));
        s->data = pre->data;
        s->next = L->next;
        L->next = s;
        pre = pre->next;
    }
    return L;


}


int main(){
    LinkList L;
    InitList(L);

    List_headInsert(L);

   LNode *p = L->next;
   while(p){
       printf("%d \n",p->data);
       p=p->next;
   }

   reverseList(L);
    printf("--------------逆置后---------------- \n");
    LNode *p1 = L->next;
    while(p1){
        printf("%d \n",p1->data);
        p1=p1->next;
    }



    return 0;
}

你可能感兴趣的:(ds,算法,数据结构)