链表的简单逆置

   

7-4 单向链表4(10 分)

定义单向链表:输入若干个正整数(输入-1为结束标志),要求按输入数据的逆序并输出。

输入输出示例:括号内为说明

输入样例:

1 2 3 4 5 6 7 -1

输出样例:

7 6 5 4 3 2 1

一个简单的链表逆置,思路比较简单。

    以下是代码内容。

#include <stdio.h>

#include <stdlib.h>
struct Node
{
    int data;
    struct Node *next;
};
struct Node *createlist()
{
    int flag=0;
    int x;
    struct Node *head,*p;
    p=(struct Node *)malloc(sizeof(struct Node));
    while(1)
    {
        scanf("%d",&x);
        if(x==-1)
            break;
        struct Node *tmp;
        tmp=(struct Node *)malloc(sizeof(struct Node));
        tmp->data=x;
        tmp->next=NULL;
        if(!flag)
        {
            head=tmp;
            flag=1;
        }
        else
        {
            p->next=tmp;
        }
        p=tmp;
    }
    return head;
}
struct Node *reverse(struct Node *head)
{
    struct Node *newhead,*p;
    newhead=(struct Node *)malloc(sizeof(struct Node));
    newhead->next=NULL;
    p=head;
    while(p)
    {
        struct Node *tmp=(struct Node *)malloc(sizeof(struct Node));
        tmp->data=p->data;
        tmp->next=newhead->next;
        newhead->next=tmp;
        p=p->next;
    }
    return newhead->next;
}
void printfList(struct Node *head)
{
    int flag=0;
    struct Node *p=head;
    while(p)
    {
        if(!flag)
        {
            printf("%d",p->data);
            flag=1;
        }
        else
        {
            printf(" %d",p->data);
        }
        p=p->next;
    }
}
int main()
{
    struct Node *head=NULL,*head1=NULL;
    head=createlist();
    head1=reverse(head);
    printfList(head1);
    return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_40750577/article/details/80039577
今日推荐