链表的逆置

数据结构实验之链表三:链表的逆置

Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Sample
Input
12 56 4 6 55 15 33 62 -1

Output
62 33 15 55 6 4 56 12

Hint
不得使用数组。

第一种:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    struct node *head,*p,*q;
    int x;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    while(~scanf("%d",&x))//输入
    {
        if(x==-1)
            break;
        else
        {
            p=(struct node *)malloc(sizeof(struct node));//
            p->data=x;//赋值
            p->next=head->next;//p所指向的结点插入头结点之后
            head->next=p;
        }
    }
    q=head->next;
    while(q)//输出
    {
        if(q->next==NULL)
            printf("%d\n",q->data);
        else
            printf("%d ",q->data);
        q=q->next;
    }
    return 0;
}

第二:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat()
{
    int a;
    struct node *head,*p,*tail;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;//申请一个头节点让它为空,让尾指针指向
    while(scanf("%d",&a)&&a!=-1)
    {
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        p->next=NULL;//p现在是一个存放了数据和指针的结点
        tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
        tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
    }
    return head;
};
void creat1(struct node *head)
{
    struct node *p,*q;
    p=head->next;
    head->next=NULL;
    q=p->next;//保存指向他的地址号
    while(p!=NULL)
    {
        p->next=head->next;//是逆置,就是要把遍历的结点插到头结点后面,插入的时候先保存插入结点的指针域
        head->next=p;
        p=q;//p插入完毕,进行下一个结点的操作,p=q就能让指针指向后一个
        if(q)
            q=p->next;//如果q没到最后才往后指
    }
};
void print(struct node *head)
{
    int n=0;
    struct node *p;
    p=head->next;
    while(p)//只要p不为空
    {
        n++;
        if(n==1)
            printf("%d",p->data);
        else
            printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
        p=p->next;
    }
    printf("\n");//n保证空格数量完全一致
}
int main()
{
    struct node *h1;
    h1=creat();
    creat1(h1);
    print(h1);
    return 0;
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值