逆置单链表

  • Post author:
  • Post category:其他


建立长度为n的单链表,然后将其数据元素逆置,即第1个元素变为最后一个元素,第2个元素变为倒数第2个元素,以此类推,最后一个元素变为第1个元素。(处理的数据类型为字符型。必须使用链表完成。)

Description

第一行为链表长度n;

第二行为链表中的n个数据元素的值。

Input

逆置后的原始的值。

Output

1
2
3

10
ABCDEFGHIJ

Sample Input

1
2

J I H G F E D C B A

#include <iostream>
#include <malloc.h>
using namespace std;
 
typedef struct node{
    char data;
    struct node *next;
}LinkList;
 
int main(){
    int n;
    cin>>n;
    LinkList *l,*body;
    l=(LinkList*)malloc(sizeof(LinkList));
    l->next=NULL;
    char ch;
    for(int i=0;i<n;i++){
        cin>>ch;
        body=(LinkList*)malloc(sizeof(LinkList));
        body->data=ch;
        body->next=l->next;
        l->next=body;
    }
    LinkList *head=l->next;
    while (head->next!=NULL) {
        cout<<head->data<<' ';
        head=head->next;
    }
    cout<<head->data<<' ';
    return 0;
}



版权声明:本文为qq_38619366原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。