链表的逆置

5.链表的逆置:

已知head指向一个带头节点的单向链表,链表中每个结点包含数据域和指针域。用链表实现该链表的逆置,并输出。

例如:

输入:5     整数表示要输入的字符个数;

   abcde

输出: edcba

注意:不允许通过改变每个节点的数据域来实现效果,必须改变链表连接顺序发生逆置。

我写的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node
{
    char date;
    struct Node *next;
};
struct Node *CreateList();
void Convert(struct Node *head);
void Print(struct Node *head);
void FreeList(struct Node *head);

int main()
{
    struct Node *head;
    int n;
    scanf("%d", &n);
    head = CreateList(n);
    Convert(head);
    Print(head);
    FreeList(head);
    return 0;
}

struct Node *CreateList(int n)
{
    struct Node *p, *q, *head;
    int i;
    p = (struct Node *)malloc(sizeof(struct Node));
    head = p;
    q = p;
    for(i = 0; i <= n; i++)
    {
        p = (struct Node *)malloc(sizeof(struct Node));
        scanf("%c", &p->date);
        q->next = p;
        q = p;
    }
    q->next = NULL;
    return head;
}
void Convert(struct Node *head)
{
    struct Node *p, *q, *r;
    p = head->next;
    q = head->next;
    r = head;
    while(q->next != NULL)
    {
        q = q->next;
        r = r->next;
    }
    head->next = q;
    q->next = r;
    while(q != p)
    {
        q = p;
        while(q->next != r)
        {
            q= q->next;
        }
        r->next = q;
        r = q;
    }
    p->next = NULL;
    return;
}

void Print(struct Node *head)
{
    struct Node *p;
    p = head->next;
    while(p != NULL)
    {
        printf("%c", p->date);
        p = p->next;
    }
    return;
}

void FreeList(struct Node *head)
{
    struct Node *p, *q;
    p = head;
    while(p != NULL)
    {
        q = p->next;
        free(p);
        p = q;
    }
    return;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值