试写一道算法,实现单链表的就地逆置(反转),即利用原表的存储空间将线性表(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;
}