单链表就地转置

试写一道算法,实现单链表的就地逆置(反转),即利用原表的存储空间将线性表(a1,a2,⋯an)逆置(反转)为(an⋯ ,a2,a1​)。
输入格式

输入共有两行,第一行为线性表长度 n(0≤n≤26)。

第二行共有 n 个大写字母,为顺序输入的线性表的元素,每两个大写字母之间一个空格。
输出格式

输出只有一行,为逆置后的线性表元素的顺序输出。每两个大写字母之间一个空格,最后一个大写字母后面没有空格。

#include <stdio.h>
typedef struct Node{
    char data;
    struct Node *next;
}Node,*LinkedList;

LinkedList insert(LinkedList head, Node *node, int index) {
    if (head == NULL) {
        if(index != 0) {
            return head;
        }
        head = node;
        return head;
    }
    
    if (index == 0) {
        node->next = head;
        head = node;
        return head;
    }
    Node *current_node = head;
    int count = 0;
    while(current_node->next != NULL && count < index - 1) {
        current_node = current_node->next;
        count++;
    }
    if (count == index - 1) {
        node->next = current_node->next;
        current_node->next = node;
    }
    return head;
}

void out_put(LinkedList head) {
    if (head == NULL) {
        return ;
    }
    Node *current_node = head;
    while(current_node != NULL && current_node->data != 'p') {
        if(current_node != head) 
            printf(" ");
        printf("%c",current_node->data);
        current_node = current_node->next;
    }
    printf("\n");
}

LinkedList reverse(LinkedList head){
    if (head == NULL) {
        return head;
    }
    Node *current_node = head->next;
    head->next = NULL;
    Node *next_node;
    while(current_node != NULL) {
        next_node = current_node->next;
        current_node->next = head;
        head = current_node;
        current_node = next_node;
    }
    return head;
}
void main(){
    int n;
    char m[27] = "\0";
    scanf("%d",&n);
    //printf("n=%d\n",n);
    LinkedList linkedlist = NULL;
    for (int i = 0; i < n; i++) {
        scanf(" %c",&m[i]);
        Node *node = (Node *)malloc(sizeof(Node));
        node->data = m[i];
        node->next = NULL;
        //printf("m[i]=%c ",m[i]);
        linkedlist = insert(linkedlist, node, i);
        //out_put(linkedlist);
    }
        
        linkedlist = reverse(linkedlist);
        out_put(linkedlist);
    return 0;
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yitahutu79

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

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

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

打赏作者

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

抵扣说明:

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

余额充值