C语言 链表尾插入和逆序

本文介绍了一种链表逆序的方法,仅需一次遍历并使用三个指针即可完成。通过具体的C语言代码示例详细展示了如何创建链表、进行逆序操作、打印链表及释放内存的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表逆序只需要一次遍历,用三个指针。


#include <stdio.h>

#include <stdlib.h>

struct Node
{
    char ch;
    struct Node *next;
};

void add(struct Node *head,char ch)//尾插入
{
    struct Node *tmp = head;
    struct Node *newnode;
    while(NULL != tmp->next)
    {
        tmp = tmp->next;
    }
    newnode = (struct Node *)malloc(sizeof(struct Node));
    
    newnode->ch = ch;
    tmp->next = newnode;

    newnode->next = NULL;
}

void reversed_list(struct Node *head)//链表逆序
{
    struct Node *tmp = head->next;
    struct Node *p = head->next->next;
    struct Node *q = p->next;

    while(NULL != q)
    {
        p->next = tmp;
tmp = p;
p = q;        
q = q->next;
    }
    p->next = tmp;
    head->next->next = NULL;
    head->next = p;
}

void print_list(struct Node *head)//显示全部的节点
{
    struct Node *tmp = (head->next);


    while(tmp != NULL)
    {
        printf("%c ",tmp->ch);
tmp = tmp->next;
    }
    printf("\n");
}

void release_all(struct Node **head)//释放所有
{
    struct Node *tmp = (*head);
    struct Node *p;

    while(NULL != tmp->next)
    {
        p = tmp->next;
        tmp->next = p->next;
free(p);
    }
    free(*head);
    (*head) = NULL;
    
}

int main()
{
    struct Node *head;
    char ch;
    int i;
    
    head = (struct Node *)malloc(sizeof(struct Node));
    head->next = NULL;

    for(i = 0; i < 5; i++)
    {
        printf("输入:");
        scanf("%c",&ch);
getchar();
        add(head,ch);
    }

    reversed_list(head);

    print_list(head);

    release_all(&head);

    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值