试写一道算法,实现单链表的就地逆置(反转),即利用原表的存储空间将线性表(a1,a2,⋯an)逆置(反转)为(an⋯ ,a2,a1)。
输入格式
输入共有两行,第一行为线性表长度 n(0≤n≤26)。
第二行共有 n 个大写字母,为顺序输入的线性表的元素,每两个大写字母之间一个空格。
输出格式
输出只有一行,为逆置后的线性表元素的顺序输出。每两个大写字母之间一个空格,最后一个大写字母后面没有空格。
这里需要注意的是,输入数据的时候利用 \n 空格 吃掉输入的格式
#include<stdio.h>
#include<stdlib.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;
}
}
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;
}
LinkedList reverse(LinkedList head){
if(head == NULL){
return head;
}
Node *current_node, *next_node;
current_node = head->next;
head->next = NULL;
while(current_node != NULL){
next_node = current_node->next;
current_node->next = head;
head = current_node;
current_node = next_node;
}
return head;
}
void output(LinkedList head){
if(head == NULL){
return;
}
Node *current_node = head;
while(current_node != NULL){
if(current_node != head){
printf(" ");
}
printf("%c",current_node->data);
current_node = current_node->next;
}
}
int main(){
int n;
scanf("%d\n", &n);
LinkedList linkedlist = NULL;
for(int i = 0; i < n; i++){
Node *node = (Node *)malloc(sizeof(Node));
scanf("%c ", &node->data);
//printf("%c\n",node->data);
node->next = NULL;
linkedlist = insert(linkedlist, node, i);
}
linkedlist = reverse(linkedlist);
output(linkedlist);
return 0;
}
网友评论