英文字母循环移动问题的正规解法
/*题目:对A-Z26个英文字母,根据指定的数字,将其循环移动,例如
ABCDEFGHIJKLMNOPQRSTUVWXYZ
输入3,得到
DEFGHIJKLMNOPQRSTUVWXYZABC
输入-3,得到
XYZABCDEFGHIJKLMNOPQRSTUVW
思路:使用双向循环链表来实现
*/
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef int status;
typedef struct node
{
ElemType data;
struct node *prior;
struct node *next;
} node, *list;
status init(list *L)
{
node *p, *q;
int i;
*L = (list)malloc(sizeof(node));
if (!(*L)) return ERROR;
(*L)->next = (*L)->prior = NULL;
p = (*L);
for (i=0; i<26; i++)
{
q = (node*)malloc(sizeof(node));
if (!q) return ERROR;
q->data = 'A'+i;
q->prior = p;
q->next = p->next;
p->next = q;
p = q;
}
// 形成闭环:
p->next = (*L)->next;
(*L)->next->prior = p;
return OK;
}
void caesar(list L, int n)
{
node *p = L->next;
if (n>0)
{
do
{
p = p->next;
} while (--n);
}
if (n<0)
{
do
{
p = p->prior;
} while (++n);
}
L->next = p;
}
int main()
{
list L = NULL;
int i = 0, n = 0;
node *p = NULL;
init(&L);
p = L->next;
for (i=0; i<26; i++)
{
printf("%c", p->data);
p = p->next;
}
printf("\n");
printf("请输入一个整数:");
scanf("%d", &n);
caesar(L, n);
p = L->next;
for (i=0; i<26; i++)
{
printf("%c", p->data);
p = p->next;
}
return 0;
}
页:
[1]