改变字符的顺序,不用额外存储空间。 改变前:a1?a2......am?b1?b2......bn 改变后:b1?b2......bn?a1?a2......am 如A?B?C?D?E?F?G变成E?F?G?A?B?C?D。用链表实现。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
typedef struct Node {
char val;
struct Node* next;
}ListNode;
ListNode* rotate(ListNode* head, int k) {
if (k == 0 || head == NULL || head->next == NULL) return head;
int n = 1;
ListNode* iter = head;
while (iter->next != NULL) {
iter = iter->next;
n++;
}
int add = n - k % n;
if (add == n) return head;
iter->next = head;
while (add--) iter = iter->next;
ListNode* ret = iter->next;
iter->next = NULL;
return ret;
}
ListNode* creatlist_r(char str[],int n)
{
int i;
ListNode*head=NULL,*p,*r=NULL;
for (i = 0; i < n; i++)
{
p= (ListNode*)malloc(sizeof(ListNode));
p->val = str[i];
p->next = NULL;
if (head == NULL)
{
head = p;
r = p;
}
r->next = p;
r = p;
}
return head;
}
void print(ListNode* head)
{
if (head == NULL)
return;
ListNode* p = head;
while (p)
{
printf("%c ",p->val);
p = p->next;
}
printf("\n");
}
int main()
{
ListNode* head;
char str[] = { 'A','B','C','D','E','F','G' };
head=creatlist_r(str,7);
head = rotate(head,3);//右移3
print(head);
return 0;
}
|