C语言-指针练习-21

题目:

单链表就地逆置

源代码:

#include <stdio.h>
#include <stdlib.h>
struct DATA
{
    int num;
};
struct NODE
{
    struct DATA data;
    struct NODE * next;
};
struct HEAD
{
    struct NODE * first;
    struct NODE * tail;
};
void initialization(struct HEAD * head);
void create_node(struct HEAD * head,int num);
void node_print(struct HEAD * head);
void inversion_linked(struct HEAD * head);
int main()
{
    struct HEAD head;
    int num,next;
    initialization(&head);
    printf("请输入你要插入的数字: ");  
    while(scanf("%d",&num))
    {
        create_node(&head,num);
        if((next = getchar()) && next != 10 && next != 32) ungetc(next,stdin); 
        else if(next == 10) break;
    }
    inversion_linked(&head);
    printf("逆序的结果是: ");
    node_print(&head);
    return 0;
}
void initialization(struct HEAD * head)
{
    head->first = (struct NODE *) malloc (sizeof(struct NODE));
    head->first->next= NULL;
}
void create_node(struct HEAD * head,int num)
{
    struct NODE * tmp_pointer = (struct NODE *) malloc (sizeof(struct NODE));
    tmp_pointer->data.num = num;
    tmp_pointer->next = NULL;
    if(head->first->next == NULL)
    {
        head->first->next = head->tail = tmp_pointer;
    }
    else
    {
        head->tail->next = tmp_pointer;
        head->tail = tmp_pointer;
    }
}
void node_print(struct HEAD * head)
{
    struct NODE * pointer = head->first->next;
    while(pointer != NULL)
    {
        printf("%d ",pointer->data.num);
        pointer = pointer->next;
    }
}
void inversion_linked(struct HEAD * head)
{
    struct NODE * tmp = head->first->next->next;
    struct NODE * tmp_tail;
    head->tail = head->first->next;
    head->tail->next = NULL;
    tmp_tail = head->tail;
    head->first->next = tmp;
    while(head->first->next)
    {
        tmp = head->first->next->next;
        head->first->next->next = head->tail;
        head->tail = head->first->next; 
        head->first->next = tmp;
    }
    
    head->first->next = head->tail;
    head->tail = tmp_tail;
}

演示效果:


如果朋友你感觉文章的内容对你有帮助,可以点赞关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是小天才哦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值