单链表的反向

Reserve函数

void ReverseList(pLink plink)
{
    pNode p1,p2,p3;
    p1=plink->head->next;
    p2=p1->next;
    p1->next = NULL;
    while (p2) {
        p3=p2->next;
        p2 ->next = p1;
        p1 = p2;
        p2 = p3;
    }
    plink->head->next = p1;
    return ; 
}

对应的链表和相应操作

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

typedef int Elementtype;

typedef struct node {
    Elementtype data;
    struct node* next;
} Node,*pNode ;

typedef struct {
    Node *head,*tail;
} Link,*pLink;

pLink CreateList(void);
void AddFromHead(pLink plink,Elementtype data);
void AddFromTail(pLink plink,Elementtype data);
void PrintList(pLink plink);
void ReverseList(pLink);
void FreeList(pLink);

int main()
{
    FILE* fp= fopen("review.in","r");
    int n;
    pLink plink = CreateList();
    while (fscanf(fp,"%d",&n) != EOF) {
        //AddFromHead(plink,n);
        AddFromTail(plink,n);
    }
    PrintList(plink);
    ReverseList(plink);
    PrintList(plink);
    FreeList(plink);
    fclose(fp);
    return 0;
}

pLink CreateList(void)
{
    pLink plink = (pLink)malloc(sizeof(Link));
    plink->head = plink->tail = (pNode)malloc(sizeof(Node));
    plink->head->next = NULL;
    return plink; 
}

void AddFromHead(pLink plink,Elementtype data)
{
    pNode p = (pNode)malloc(sizeof(Node));
    p->data = data;
    p->next = plink->head->next;
    plink->head->next = p;
    return ;
}

void AddFromTail(pLink plink,Elementtype data)
{
    pNode p = (pNode)malloc(sizeof(Node));
    plink->tail->next = p;
    p->next = NULL;
    p->data = data;
    plink->tail = p;
    return ;

    /*
    pNode q,end,p = (pNode)malloc(sizeof(Node));
    for (q=end; q ;q=q->next) {
        end = q;
    }
    p->data =data;
    end->next = p;
    p->next = NULL;
    return ;
    */
}

void PrintList (pLink plink)
{
    pNode p;
    for (p=plink->head->next;p;p=p->next) {
        printf("%d ",p->data);
    }
    printf("\n");
    return ;
}

void ReverseList(pLink plink)
{
    pNode p1,p2,p3;
    p1=plink->head->next;
    p2=p1->next;
    p1->next = NULL;
    while (p2) {
        p3=p2->next;
        p2 ->next = p1;
        p1 = p2;
        p2 = p3;
    }
    plink->head->next = p1;
    return ; 
}

void FreeList(pLink plink)
{
    pNode p,q;
    for (q=plink->head,p=plink->head->next;p;q=p,p=p->next) {
        free(q);
    }
    free(q);
    free(plink);
    return ; 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值