38-5

编写带头结点的算法,就地逆置

小心断链

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

typedef struct node{
    int data;
    struct node *next;
}LNode,*LinkList;

void TailCreate(LinkList &L)
{
    L=(LinkList)malloc(sizeof(LNode));
    L->next=NULL;
    LNode *p,*r=L;
    int x;
    scanf("%d",&x);
    while(x!=999)
    {
        p=(LNode*)malloc(sizeof(LNode));
        p->data=x;
        p->next=NULL;
        r->next=p;
        r=p;
        scanf("%d",&x);
    }
}

void displayList(LinkList L)
{
    LNode *p=L->next;
    while(p!=NULL)
    {
        printf("%d  ",p->data);
        p=p->next;
    }
}

void Reverse(LinkList &L)
{
    LNode *s,*p=L->next;  
    L->next=NULL;
    while(p!=NULL)
    {
        s=p->next;        //s防止断链,p使用头插法插入
        p->next=L->next;
        L->next=p;
        p=s;
    }
}

int main()
{
    LinkList L;
    TailCreate(L);
    displayList(L);
    printf("\n");
    Reverse(L);
    displayList(L);
    return 0;
}

 

posted on 2023-10-05 20:44  四马路弗洛伊德  阅读(25)  评论(0)    收藏  举报

导航